简体   繁体   中英

How to use LEFT JOIN in this query

I have the following query

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

I need to use LEFT JOIN on gallery , gallery_images tables (to be able to get interview.title even when there is no gallery or default image)

Thanks much

UPDATE


The problem, is in second LEFT JOIN. I can't make them to work together correctly. When i try

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'

You know what you need to do. Google is your friend?

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

Try that one:

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;

Don't mix ANSI-89 style and ANSI-92 style joins.

I found same question in SO, here .

So my query must look like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM