1

我在 MySQL 中有 3 个表

USERS
uid
email
password
created

这是包含所有用户的所有记录的表

PHOTOS
iid
uid
file
thumb
uploaded

这是保存每个用户发布的所有照片的表格

COMMENTS
cid
iid
uid
message
created

这是保存每个用户对每张照片的所有评论的表格

我想要的是一个查询,它可以为每个唯一( )用户检索COUNT每张照片的评论数量() 。DISTINCT例如(结果输出必须是):

comment_amount  by_user on_picture
3               1       1
2               2       1
2               1       2
5               2       2
6               2       3

所以输出可以告诉我们它是否被格式化为(示例)

3 comments posted by USER1 on PICTURE1
2 comments posted by USER2 on PICTURE1

2 comments posted by USER1 on PICTURE2
5 comments posted by USER2 on PICTURE2

6 comments posted by USER2 on PICTURE3

到目前为止我所拥有的是

SELECT 
users.uid
FROM users
INNER
    JOIN photos
    ON photos.uid = users.uid
INNER
    JOIN comments
    ON comments.iid = photos.iid

这是沙盒测试

http://sqlfiddle.com/#!2/955d5/1

但我不知道下一步该怎么做,任何帮助将不胜感激!MySQL 以外的任何语言也应该可以工作!

4

4 回答 4

1

您的查询可能类似于:

SELECT users.uid AS UserId, count(comments.cid) AS CountComments
FROM users
INNER
    JOIN photos
    ON photos.uid = users.uid
INNER
    JOIN comments
    ON comments.iid = photos.iid
group by users.uid

你可以测试一下

如果要添加图像 ID,可以将 photo.iid 添加到分组依据

SELECT users.uid AS UserId, count(comments.cid) AS CountComments, 
  photos.iid as PhotoId
  FROM users
INNER
    JOIN photos
    ON photos.uid = users.uid
INNER
    JOIN comments
    ON comments.iid = photos.iid
group by users.uid, photos.iid

看看这个

于 2012-10-10T21:12:06.780 回答
1
SELECT count(*) AS comment_amount, users.uid AS by_user, photos.iid AS on_picture
FROM users
INNER
    JOIN photos
    ON photos.uid = users.uid
INNER
    JOIN comments
    ON comments.iid = photos.iid
group by users.uid, photos.iid

要不就

SELECT count(*) AS comment_amount, uid AS by_user, iid AS on_picture
FROM comments

如果您只需要评论表中的数据

于 2012-10-10T21:14:38.620 回答
1

我会先做 GROUP:

SELECT  iid, uid, count(*)
FROM comments
GROUP BY  iid, uid

然后加入相关表格。

于 2012-10-10T21:18:59.077 回答
0
    SELECT 
    users.uid, photos.iid, count(*) nb
    FROM users
    INNER
    JOIN photos
    ON photos.uid = users.uid
INNER
    JOIN comments
    ON comments.iid = photos.iid

group by users.uid, photos.iid

感谢 sql fiddle 链接,我不知道。

于 2012-10-10T21:14:41.603 回答