我在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之外的任何语言都应该可以工作!
答案 0 :(得分: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
你可以test it
如果您想添加图片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
答案 1 :(得分: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
如果您只需要评论表中的数据
答案 2 :(得分:1)
我会首先进行GROUP:
SELECT iid, uid, count(*)
FROM comments
GROUP BY iid, uid
之后加入相关表格。