我的数据库有4个表:
用户
图片
user_follow
评论
我尝试查询以获取我和我朋友的所有照片 1)仅当用户在“images”表中有图片时才必须显示行 2)只有来自我和我的朋友的图像(取决于“user_follow”表) 3)计算每张图片的评论
我的查询是:
SELECT u.username as user, i.image as user_image, p.image, UNIX_TIMESTAMP(p.date) as date, COALESCE ( imgcount.cnt, 0 ) as comments
FROM users u
LEFT JOIN user_follow f ON u.id = f.follow_id
LEFT JOIN images p ON p.user_id = u.id
LEFT JOIN images i ON i.id = (SELECT b.id FROM images AS b where p.user_id = b.user_id ORDER BY b.id DESC LIMIT 1)
LEFT JOIN (SELECT image_id, COUNT(*) as cnt FROM commentaries GROUP BY image_id ) imgcount ON p.id = imgcount.image_id
WHERE f.user_id = 3 OR p.user_id = 3
ORDER BY p.date DESC
每个图像的注释计数sql行在此查询中正常工作
LEFT JOIN (SELECT image_id, COUNT(*) as cnt FROM commentaries GROUP BY image_id ) imgcount ON p.id = imgcount.image_id
在这一行中,我尝试将用户最后一次上传的图像作为“图像”表中的头像
LEFT JOIN images i ON i.id = (SELECT b.id FROM images AS b where p.user_id = b.user_id ORDER BY b.id DESC LIMIT 1)
这个查询点没有正确返回结果,因为它显示我没有图片的朋友和我自己的图片不好(在数据库中我有2行与我的user_id:3)但是sql返回4
答案 0 :(得分:2)
如果我理解正确,似乎你已经使它变得比它需要的复杂得多。你没有图片的朋友获得记录的原因是因为你正在使用LEFT JOIN。将其更改为INNER JOIN,您将只获得与连接条件匹配的记录。
我认为您正在寻找以下内容。你需要做一些调整,但希望这会有所帮助。
SELECT u.username as user, i.image as user_image, count(*) as comments
FROM users u
INNER JOIN user_follow f ON u.id = f.follow_id
INNER JOIN images p ON p.user_id = u.id
INNER JOIN commentaries c ON c.image_id = p.id
WHERE u.user_id = 3
GROUP BY u.username, i.image;