如何关联两个表以显示名称行而不是mysql + pdo中的id [英] How relating two tables to show name row and not the id in mysql+pdo
问题描述
当显示表1的结果时,我不知道如何在表2中显示行名而不是其id.
I don't know how show the name of the row in table 2 instead of his id when show it results of table 1.
让我解释一下:
我在innoDB中有此表:
I have this tables in innoDB:
- PACIENTES(table name).
* id (int)
* nombre (varchar)
* apellido (varchar)
* pais (varchar)
* departamento (varchar)
* ciudad (varchar)
- lista_paises(table name).
* id (int)
* opcion (varchar)
- lista_departamento(table name).
* id_departamento (int)
* opcion (varchar)
* relacion (int)-----relation with table lista_paises----
- MUNICIPIOS(table name).
* id_municipio (int)
* id_departamento (int)-----relation with table lista_departamento----
* municipio_nombre (varchar)
在餐桌上,我已经保存了lista_paises,lista_departamento和市政之类的ID,例如
in table pacientes I have save the id of lista_paises, lista_departamento, municipios like
---- id ---- nombre ----- apellido ----- pais ---- departamento ---- ciudad
----id----nombre-----apellido-----pais----departamento----ciudad
1 Juan Perez 10 178 198
我需要在页面上显示
id nombre apellido pais departamento ciudad
1 Juan Perez El Salvador Santa Ana Santa Ana
我有这句话(其他带有departamento的句子是相同的),但是没有显示真正的departamento或真正的ciudad ...总是只显示一个id为1的departamento或muunicipio.
I have this sentence(the other sentence with departamento is the same) but not show the real departamento or the real ciudad...always show only one departamento or municipio with id 1
<?
$sql = "SELECT PACIENTES.ciudad, MUNICIPIOS.municipio_nombre
FROM PACIENTES INNER JOIN MUNICIPIOS
ON MUNICIPIOS.id_departamento = PACIENTES.ciudad";
$stmt = $conn->prepare($sql);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$municipio_nombre = $row['municipio_nombre'];
?>
<td><? echo $municipio_nombre ?></td>
很抱歉,如果我的问题太长或不能很好地理解,但是老实说我不知道如何更好地解释这个问题……希望您能为我提供帮助
I'm sorry if my question is so long or not understand very well but to be honest I don't know how explain better this question... I hope you can help me with this
推荐答案
您在表中有nombre_municipio
,在查询中有MUNICIPIOS.municipio_nombre
.
You have nombre_municipio
in table and MUNICIPIOS.municipio_nombre
in query.
也ON MUNICIPIOS.id_departamento = PACIENTES.ciudad
要将varchar与int进行比较
Also ON MUNICIPIOS.id_departamento = PACIENTES.ciudad
is comparing varchar with int
要加入MUNICIPIOS
和PACIENTES
,您需要在MUNICIPIOS
表中具有与PACIENTES.id
相关的字段,例如(MUNICIPIOS.id_pacientes
)
To Join MUNICIPIOS
and PACIENTES
you require to have field related to PACIENTES.id
in MUNICIPIOS
table eg (MUNICIPIOS.id_pacientes
)
$sql = "SELECT PACIENTES.ciudad, MUNICIPIOS.municipio_nombre
FROM PACIENTES
INNER JOIN MUNICIPIOS
ON PACIENTES.id = MUNICIPIOS.id_pacientes";
这篇关于如何关联两个表以显示名称行而不是mysql + pdo中的id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!