我有两张桌子:
NEWS (id, news_content)
NEWS_VOTES (vote, news_id)
我应该在NEWS上选择(*)所有值,并在NEWS_VOTES表上计算投票,其中news.id和news_votes.new_id是相同的。
更明确的解释是:
否定投票:
SELECT count(*) FROM NEWS_VOTES WHERE news_id = (same ID) AND vote = 0
积极投票:
SELECT count(*) FROM NEWS_VOTES WHERE news_id = (same ID) AND vote = 1
我需要在一次查询中执行此操作。
网站上的输出将是“这条新闻得到57张正面投票和67张反对票。”
谢谢。
聚苯乙烯。我使用MYSQL。
答案 0 :(得分:5)
假设正面投票有vote=1
:
select
n.id,
n.news_content,
(select count(*) from news_votes where news_id=n.id and vote = 1) as positive_votes,
(select count(*) from news_votes where news_id=n.id and vote = 0) as negative_votes
from news n
答案 1 :(得分:3)
SELECT n.id, n.news_content,
COUNT(v1.vote) AS negative,
COUNT(v2.vote) AS positive
FROM news n
LEFT JOIN news_votes v1 ON v1.news_id = n.id
LEFT JOIN news_votes v2 ON v2.news_id = n.id
HAVING v1.vote = 0 AND HAVING v2.vote = 1
GROUP BY v1.news_id, v2.news_id
ORDER BY id DESC
答案 2 :(得分:1)
select id, news_content,
coalesce(v.positive, 0) as positive,
coalesce(v.negative, 0) as negative
from news n
left join (
select news_id,
sum(case when vote = 1 then 1 else 0 end) as positive,
sum(case when vote = 0 then 1 else 0 end) as negative
from news_votes
group by news_id
) v on n.id = v.news_id
答案 3 :(得分:1)
试试这个 -
SELECT
n.*,
COUNT(IF(nv.vote = 1, 1, NULL)) Positive_Votes,
COUNT(IF(nv.vote = 0, 1, NULL)) Negative_Votes
FROM news n
LEFT JOIN NEWS_VOTES nv
ON nv.news_id = n.id
GROUP BY
n.id
如果vote = 1表示正投票,则投票= 0表示反对投票。
答案 4 :(得分:0)
选择 (SELECT count(*)FROM NEWS_VOTES WHERE news_id =(相同ID)AND vote = 0)positive_votes, (SELECT count(*)FROM NEWS_VOTES WHERE news_id =(相同ID)AND vote = 1)negative_votes 来自双重;