假设我有 4 个表:
'users'(id,username),
'photos'(id,user_id,name),
'photos_comments'(id,photo_id,user_id,text),'photos_likes'(id,photo_id,user_id,测试)。
我想计算每个用户在他所有上传的照片中的所有评论和喜欢的总和。为此,我正在尝试构建一个查询:
SELECT users.*,
(SELECT SUM(count) as rating FROM(
SELECT COUNT(*) as count FROM photos_likes
WHERE photos_likes.photo_id IN (SELECT photos.id FROM photos WHERE photos.user_id = users.id)
UNION
SELECT COUNT(*) as count FROM photos_comments
WHERE photos_comments.photo_id IN (SELECT photos.id FROM photos WHERE photos.user_id = users.id)
) as total_rating) as rating FROM users
它返回“WHERE 子句中的未知 users.id 列”错误。所以看起来它在大多数内部查询中看不到 users 表。我不明白为什么会发生这种情况,因为另一个类似的查询可以正常工作:
SELECT users.*,
(SELECT COUNT(*) as count FROM photos_likes
WHERE photos_likes.photo_id IN (SELECT photos.id FROM photos WHERE photos.user_id = users.id)) as likes_count,
(SELECT COUNT(*) as count FROM photos_comments
WHERE photos_comments.photo_id IN (SELECT photos.id FROM photos WHERE photos.user_id = users.id)) as comments_count FROM users
在此查询中,它可以从大多数内部查询中的用户表行中获取 id。为什么它会这样工作?感谢帮助。