我有以下查询来选择照片,标签和一些基本用户信息:
SELECT photos.*, GROUP_CONCAT(tags.tag SEPARATOR ', ') AS photo_tags
FROM photos
INNER JOIN users
ON photos.upload_by = users.user_id
INNER JOIN tags_photos
ON tags_photos.photo_id = photos.photo_id
INNER JOIN tags
ON tags.tag_id = tags_photos.tag_id
WHERE photos.status = '$status'
AND photos.photo_id IN (SELECT photos.photo_id
FROM photos
JOIN tags_photos
ON photos.photo_id = tags_photos.photo_id
JOIN tags
ON tags_photos.tag_id = tags.tag_id)
GROUP BY photos.photo_id
ORDER BY status, upload_date;
效果很好,唯一的例外是如果照片没有标签,则不会返回该照片。即使没有标签,我仍然希望它仍然可以返回照片。
有人有任何建议吗?
答案 0 :(得分:1)
不确定为什么在WHERE子句中需要IN子查询。
SELECT photos.*, GROUP_CONCAT(tags.tag SEPARATOR ', ') AS photo_tags
FROM photos
INNER JOIN users
ON photos.upload_by = users.user_id
LEFT JOIN tags_photos
INNER JOIN tags
ON tags.tag_id = tags_photos.tag_id
ON tags_photos.photo_id = photos.photo_id
WHERE photos.status = '$status'
GROUP BY photos.photo_id
ORDER BY status, upload_date;
答案 1 :(得分:0)
您似乎需要RIGHT OUTER JOIN
和tags_photos
photos
SELECT photos.*, GROUP_CONCAT(tags.tag SEPARATOR ', ') AS photo_tags FROM photos
INNER JOIN users ON photos.upload_by = users.user_id
RIGHT OUTER JOIN tags_photos ON tags_photos.photo_id = photos.photo_id
INNER JOIN tags ON tags.tag_id = tags_photos.tag_id
WHERE photos.status = '$status' AND photos.photo_id IN (
SELECT photos.photo_id
FROM photos
LEFT OUTER JOIN tags_photos ON photos.photo_id = tags_photos.photo_id
JOIN tags ON tags_photos.tag_id = tags.tag_id
)
GROUP BY photos.photo_id ORDER BY status, upload_date;