我有两个行政区划表,如下所示。我试图获得每个教区的市政名称。
市
id | district_id | name |
---------|-------------|----------|
01 | 01 | Abc |
01 | 02 | Cba |
01 | 03 | Random |
...
教区
id | municipality_id | district_id | name |
----|-----------------|-------------|------|
03 | 01 | 01 | Abc |
09 | 01 | 02 | Zxe |
12 | 01 | 01 | Tfg |
19 | 01 | 03 | Qwe |
查询我尝试没有成功:
SELECT municipalities.Name FROM municipalities
JOIN parishes AS P
ON municipalities.id = P.municipality_id
AND municipalities.district_id = P.district_id;
名字不匹配。如何更改查询以获得每个教区的市政名称?理想情况下,结果将是这样的:
id | municipality_name | parish_name
03 | Abc | Abc
09 | Cba | Zxe
...
注意:市政当局的id列没有主键约束。
答案 0 :(得分:1)
只需在SELECT
之后添加所需的其他列,按照您希望它们返回的顺序,以逗号分隔列出所需的列:
SELECT P.id, municipalities.name, P.name
FROM municipalities
JOIN parishes as P
...
答案 1 :(得分:0)
尝试
SELECT p.id, m.name AS municipality_name, p.name AS parish_name
FROM municipalities m
JOIN parishes p ON m.id = p.municipality_id AND m.district_id = p.district_id
答案 2 :(得分:0)
只需添加表parishes
SELECT p.id, municipalities.Name, p.name
FROM municipalities
JOIN parishes AS P
ON municipalities.id = P.municipality_id
AND municipalities.district_id = P.district_id;