MySQL 对另一列 = 值的行进行计数
我有一个 While
循环,显示每行中 p.songid
(发布曲目)的 COUNT
。我实际需要的是根据 trackDeleted=0
而不是所有行来获取计数。
SELECT u.username, u.id, u.score, s.genre, s.songid, s.songTitle, s.timeSubmitted, s.userid, s.insWanted, s.bounty, COUNT(p.songid)
FROM songs s
LEFT JOIN users u ON u.id = s.userid
LEFT JOIN posttracks p ON s.songid = p.songid
WHERE paid=1 AND s.timeSubmitted >= ( CURDATE() - INTERVAL 60 DAY )
GROUP BY s.timeSubmitted ASC
LIMIT 25
我可以更新上述查询还是必须在单独的查询中?
I have a While
loop that displays the COUNT
of p.songid
(post tracks) in each row. What I actually need is to get the count based on trackDeleted=0
instead of all the rows.
SELECT u.username, u.id, u.score, s.genre, s.songid, s.songTitle, s.timeSubmitted, s.userid, s.insWanted, s.bounty, COUNT(p.songid)
FROM songs s
LEFT JOIN users u ON u.id = s.userid
LEFT JOIN posttracks p ON s.songid = p.songid
WHERE paid=1 AND s.timeSubmitted >= ( CURDATE() - INTERVAL 60 DAY )
GROUP BY s.timeSubmitted ASC
LIMIT 25
Can I update the above query or does this have to be in a separate query?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
我不确定这在 mySql 中是否有效,但在 SQL 中,您可以在连接期间进行过滤,如下所示:
I am not sure if this works in mySql but in SQL you are able to filter during the join as follows:
这取决于 trackDeleted 列在哪个表中。
如果它存在于后轨中,那就很简单
It depends in what table the trackDeleted column is.
If it lives in posttracks, then it's simple
将
trackDeleted = 0
添加到WHERE
子句中:Add
trackDeleted = 0
to yourWHERE
clause:试试这个...
您必须按 p.songid 分组。
Try this...
You must group by the p.songid.
如果您要计算歌曲 ID,则必须将其自行分组,请尝试这个。
If you are going to COUNT the song id, you must group it by it self, try this one.
将测试放入连接条件中:
或者将
COUNT(p.songid)
更改为 SUM:Either put your test in the join condition:
Or change
COUNT(p.songid)
to a SUM instead:以防万一有人像我一样偶然发现这一点,正确的答案可能是这样的:
关键是
COUNT(IF(p.trackDeleted=0, 1, NULL)) as not_deleted_count
看起来分组中的所有曲目,并且只计算那些未删除的曲目。这里的所有其他答案都错误地认为OP只想选择未删除的曲目,而他想要的是计算每个分组内未删除的曲目数量。
Just in case anyone stumbles on this, as I did, the correct answer is probably something like:
The key being
COUNT(IF(p.trackDeleted=0, 1, NULL)) as not_deleted_count
which will look at all the tracks in a grouping, and only count those that are not deleted.Every other answer in here was mistaking the OP as only wanting to select tracks that werent deleted, when what he wanted was to count the number of tracks that werent deleted inside each grouping.
试试这个。
尝试将其添加到您的代码中。如果您需要显示有多少曲目有 trackDeleted = 0,只需访问局部变量 @trackcount 即可。
try this.
try to add this to your code. just access local variable @trackcount if you need to show how many tracks have trackDeleted = 0.