SQL - 如何从同一列中选择多个表并加入多个行?

时间:2011-11-10 22:46:28

标签: mysql sql select join

如何从同一列中选择多个表并加入多行?

它不会返回painting.id_grouppainting.id_typepainting.id_location。 我确定这个SQL代码段的语法错误。

SELECT painting.id, painting.order, painting_en.url, id_portfolio.en
FROM painting
LEFT JOIN painting_en
USING ( id ) 
LEFT JOIN id_portfolio ON id_portfolio.id = painting.id_group
AND id_portfolio.id = painting.id_type
AND id_portfolio.id = painting.id_location
WHERE painting_en.url='2011-name3'
LIMIT 1

更新 它显示Showing rows 0 - 0 ( 1 total, Query took 0.0004 sec)。 删除后

AND id_portfolio.id = painting.id_type
AND id_portfolio.id = painting.id_location

它返回:

id        | order | url        |en
----------+-------+------------+-----
09518709  | 4     | 2011-name3 | NULL

但我需要回复:

id        | order | url        | group   | type          | location
----------+-------+------------+---------+---------------+---------
09518709  | 4     | 2011-name3 | realism | oil on canvas | US

1 个答案:

答案 0 :(得分:1)

您可以多次加入同一个表,只需要提供不同的别名

SELECT painting.id, 
       painting.order, 
       painting_en.url, 
       `group`.en AS `group`, 
       TYPE.en AS type, 
       location.en AS location
FROM   painting 
       LEFT JOIN painting_en 
       USING (id) 
       LEFT JOIN id_portfolio `group` 
         ON `group`.id = painting.id_group 
       LEFT JOIN id_portfolio TYPE 
         ON TYPE.id = painting.id_type 
       LEFT JOIN id_portfolio location 
         ON location.id = painting.id_location 
WHERE  painting_en.url = '2011-name3' 
LIMIT  1