简体   繁体   中英

MySQL: INNER JOIN crashes 2 LEFT JOINs if one of them returns NULL

In query:

SELECT
    i.id, i.title, i.description,
    cities.name as city,
    GROUP_CONCAT(DISTINCT station.name) as station,
    GROUP_CONCAT(DISTINCT p.url) as photos
FROM
    items i
INNER JOIN
    cities ON cities.id = i.city_id
LEFT JOIN
    item_photos p ON p.item_id = i.id
LEFT JOIN
    item_stations s ON s.item_id = i.id
INNER JOIN
    stations ON stations.id = s.station_id
WHERE i.id = ?
LIMIT 1

if rows in table item_stations don't exists, both LEFT JOINs works: returns photos and NULL for stations. but with INNER JOIN in this case query will return NULL for photos and station. How should I rewrite query to say INNER JOIN not to join tables if no needed rows in item_stations with s.item_id = i.id ?

If you truly need to do an INNER JOIN between the item_stations and the stations table, then you might want to consider using an INNER JOIN in a subquery:

SELECT
    i.id, i.title, i.description,
    cities.name as city,
    GROUP_CONCAT(DISTINCT s.name) as station,
    GROUP_CONCAT(DISTINCT p.url) as photos
FROM items i
INNER JOIN cities 
  ON cities.id = i.city_id
LEFT JOIN item_photos p 
  ON p.item_id = i.id
LEFT JOIN
(
  select item_id, name
  from item_stations s 
  INNER JOIN stations 
    ON stations.id = s.station_id
) 
  ON s.item_id = i.id
WHERE i.id = ?
LIMIT 1

Otherwise I would suggest using a LEFT JOIN between the two:

SELECT
    i.id, i.title, i.description,
    cities.name as city,
    GROUP_CONCAT(DISTINCT stations.name) as station,
    GROUP_CONCAT(DISTINCT p.url) as photos
FROM items i
INNER JOIN cities 
  ON cities.id = i.city_id
LEFT JOIN item_photos p 
  ON p.item_id = i.id
LEFT JOIN item_stations s 
  ON s.item_id = i.id
LEFT JOIN stations 
  ON stations.id = s.station_id
WHERE i.id = ?
LIMIT 1

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