我正在尝试实现此结果,“地方”表包含3种类型的地方(州,城市,屠宰场)。我想根据枚举列“类型”将它们显示为不同的列。
这是我到目前为止尝试过的:
SELECT sifs.sif_id, places.`name` as city FROM sifs
INNER JOIN places ON sifs.city_id = places.id
union all
SELECT sifs.sif_id, places.`name` as slaughter FROM sifs
INNER JOIN places ON sifs.slaughter_id = places.id
union all
SELECT sifs.sif_id, places.`name` as state FROM sifs
INNER JOIN places ON sifs.state_id = places.id
这是查询结果:
sif_id | city
15 | Pedro Juan Caballero(PRY)
15 | FRIGONORTE
15 | Amambay(PRY)
这就是我想要的:
sif_id | state | city | slaughter
15 | Amambay(PRY)| Pedro Juan Caballero(PRY)| FRIGONORTE
表格字段:
sifs:sif_id,state_id,city_id,slaughter_id 地点:名称,类型(“州”,“城市”,“屠杀”)
答案 0 :(得分:1)
我认为您需要多个join
:
SELECT s.sif_id, pc.name as city, ps.name as slaughter,
pst.name as state
FROM sifs s LEFT JOIN
places pc
ON s.city_id = pc.id LEFT JOIN
places ps
ON s.slaughter_id = ps.id LEFT JOIN
places pss
ON s.state_id = pst.id;
这使用LEFT JOIN
,因此sifs
中的所有行都在结果集中,即使某些ID没有匹配项。