如何在此查询中使用LEFT JOIN

时间:2011-02-16 17:47:05

标签: php mysql left-join

我有以下查询

SELECT
    interview_content.title `title`,
    gallery_images.img_path img
FROM
    `interview`,
    `interview_content`,
    `gallery`,
    `gallery_images`
WHERE
    `gallery_images`.`id_parrent` = `gallery`.`id`
AND
    `gallery`.`id` =  `interview`.`gallery_id`
AND
    `gallery_images`.`default` = '1'
AND
    `interview`.`id` = `interview_content`.`id_parrent`
AND
    interview_content.id_lang = '2'
ORDER BY
    interview.date DESC

我需要在gallerygallery_images表上使用LEFT JOIN(即使没有图库或默认图片也能获得interview.title

非常感谢

更新


问题出在第二个LEFT JOIN。我不能让他们正确地合作。当我尝试

SELECT
    interview_content.title `title`,
    gi.img_path img
FROM
    `interview`,
    `interview_content`
LEFT JOIN `gallery` as g ON g.`id` = `interview`.`gallery_id` 
LEFT JOIN `gallery_images` as gi ON gi.id_parrent = g.`id`
WHERE
    `interview`.`id` = `interview_content`.`id_parrent`
AND
    interview_content.id_lang = '2'
ORDER BY
    interview.date DESC

it returns //Unknown column 'interview.gallery_id' in 'on clause'

3 个答案:

答案 0 :(得分:3)

你知道你需要做什么。 谷歌是你的朋友吗?

http://en.wikipedia.org/wiki/Join_%28SQL%29#Left_outer_join

答案 1 :(得分:1)

尝试一下:

SELECT
    interview_content.title `title`,
    gallery_images.img_path img
FROM
    `interview`,
    `interview_content`,
LEFT JOIN `gallery` ON (`interview`.`gallery_id` = `gallery`.`id` AND `gallery_images`.`default` = '1'), 
LEFT JOIN `gallery_images` ON `gallery`.`id` = `gallery_images`.`id_parrent`
WHERE
    `interview`.`id` = `interview_content`.`id_parrent`
AND
    interview_content.id_lang = '2'
ORDER BY
    interview.date DESC;

答案 2 :(得分:1)

不要混用ANSI-89样式和ANSI-92样式联接。

我在SO here找到了同样的问题。

所以我的查询必须看起来像这样

SELECT
    ic.title `title`,
    gi.img_path img
FROM
    `interview` i
JOIN interview_content ic  on ic.id_parrent =  i.id AND ic.id_lang = '2'
LEFT JOIN `gallery` as g ON g.`id` = i.`gallery_id` 
LEFT JOIN `gallery_images` as gi ON gi.id_parrent = g.`id`
AND gi.`default` = '1'
WHERE
    i.`id` = ic.`id_parrent`
OPRDER BY
    `i`.`date` DESC