0

假设我有 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。为什么它会这样工作?感谢帮助。

4

2 回答 2

2

查看FROM 子句中的子查询

FROM 子句中的子查询不能是相关子查询,除非在 JOIN 操作的 ON 子句中使用。

在第二个示例中,您在where子句中使用子查询。这就是区别。

另请参见相关子查询

于 2012-11-02T09:50:08.000 回答
0
select 
    photos.userid, 
    photos.photoid, 
    count(distinct commentid), 
    count(distinct likeid),
    count(distinct commentid) + count(distinct likeid) as total
from
    photos 
         left join photos_comments on photos.photoid=photos_comments.photoid
         left join photos_likes on photos.photoid=photos_likes.photoid
group by photos.userid, photos.photoid
于 2012-11-02T09:09:27.980 回答