我想知道如何根据MySQL中的字段值返回基于count
的数字。
所以,让我们说你有一个简单的MySQL设置,如:
Users (id)
Posts (id, user_id, body)
Votes (id, post_id, user_id, vote_type)
然后你想得到前10个帖子,按照vote_type='up'
比vote_type='down'
SELECT votes.*, ((SELECT count(post_id) FROM votes AS v1 WHERE vote='up'
AND votes.post_id =v1.post_id) - (SELECT count(post_id) FROM votes AS v2
WHERE vote='down' AND votes.post_id =v2.post_id)) AS score FROM votes GROUP
BY votes.post_id ORDER BY score DESC
以上查询有效,但不会考虑没有投票的帖子,而且似乎还有更好的方法。
答案 0 :(得分:0)
试试这个
SELECT
posts.*, (a.up_count - b.down_count) as net_vote
FROM
posts
INNER JOIN (
SELECT
post_id, COUNT(*) as up_count
FROM
votes
WHERE
vote_type = 'up'
GROUP BY
post_id
) a ON a.post_id = posts.id
INNER JOIN (
SELECT
post_id, COUNT(*) as down_count
FROM
votes
WHERE
vote_type = 'down'
GROUP BY
post_id
) b ON b.post_id = posts.id
ORDER BY
net_vote DESC
LIMIT 10
答案 1 :(得分:0)
你可以使用一些连接
SELECT votes.*, ifnull(v1.count,0) - innull(v2.count,0) AS score
FROM votes
LEFT JOIN (
SELECT post_id, count(post_id) as count
FROM votes AS v1 WHERE vote='up'
GROUP BY post_id ) v1 on votes.post_id = v1.post_id
LEFT JOIN (
SELECT post_id, count(post_id)
FROM votes AS v1 WHERE vote='down'
GROUP BY post_id ) v2 on votes.post_id = v2.post_id
答案 2 :(得分:0)
试试这个:
select p.*
from posts p
left join votes v on v.post_id = p.id
group by 1, 2, 3
order by sum(vote_type = 'down') - sum(vote_type = 'up')
limit 10
注意计算扭曲次数的简单方法;在MySQL中,true为1,false为0,因此我们可以对条件求和。
如果您还想查看投票类型计数的差异,请按表达式将订单添加到选择列表中。