在查询中:
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
如果表item_stations
中的行不存在,则两个LEFT JOIN都起作用:返回照片和工作站的NULL。但在这种情况下使用INNER JOIN查询将为照片和工作站返回NULL。如果item_stations
s.item_id = i.id
中没有必要的行,我应该如何重写查询以说INNER JOIN不加入表?
答案 0 :(得分:1)
如果您确实需要在item_stations
和stations
表之间进行INNER JOIN,那么您可能需要考虑在子查询中使用INNER JOIN:
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
否则我建议在两者之间使用LEFT JOIN:
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