我正在尝试用这个查询我的数据库:
SELECT ar.email, tr.trackid, al.albumtitle, al.albumid, al.publishingdate, tr.genre, tr.tracktitle, ar.artistname, tr.reproductions, CEIL(AVG(co.rating)) AS 'media'
FROM tsn_tracks tr, tsn_albums al, tsn_artists ar, tsn_comments co
WHERE al.email=ar.email AND tr.albumid=al.albumid tr.trackid = co.trackid
GROUP BY tr.trackid
ORDER BY al.publishingdate desc
LIMIT 0, 20
我将很快解释该方案:我想按发布日期的顺序(从最近的)检索具有所有不同属性的前 20 首歌曲,特别是,用户可以对轨道发表评论并进行投票(从 1 到 5)在他们的评论中,在我的查询中我想显示每首歌的投票平均值,但是当一首歌没有收到任何评论时,它不会出现在结果集中(因为“tr .trackid = co.trackid”)。我尝试了许多不同的方法,但没有解决问题。我希望当一首歌没有任何评论时,我的查询会给我一个特定的值(例如 0)。
对不起我的英语!
最佳答案
使用 JOIN 而不是在 FROM 和 WHERE 中使用所有内容将允许您使用 LEFT JOINS。这意味着即使右侧的表(名义上)没有匹配的记录,也会检索一行。
SELECT ar.email, tr.trackid, al.albumtitle, al.albumid,
al.publishingdate, tr.genre, tr.tracktitle, ar.artistname,
tr.reproductions, CEIL(AVG(co.rating)) AS 'media'
FROM tsn_tracks tr
JOIN tsn_albums al on tr.albumid=al.albumid
JOIN tsn_artists ar ON al.email=ar.email
LEFT JOIN tsn_comments co ON tr.trackid = co.trackid
GROUP BY tr.trackid
ORDER BY al.publishingdate desc
LIMIT 0, 20
关于php - 带有 avg 的奇怪 sql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44247661/