一个基本的 sql 查询示例
我有两个表:
NEWS (id, news_content)
NEWS_VOTES (vote, news_id)
我应该选择 (*) NEWS 上的所有值,并对 NEWS_VOTES 表上的投票进行计数,其中 news.id 和 news_votes.new_id 相同。
更清楚一点的解释是:
- 我选择 NEWS 表上的所有值。
- 根据“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。
I have two tables:
NEWS (id, news_content)
NEWS_VOTES (vote, news_id)
I should be selecting (*) all values on NEWS, and also count vote on NEWS_VOTES table where news.id and news_votes.new_id are the same.
A little clearer explanation is:
- I select all values on NEWS table.
- Depending on "id" value, I also select:
Negative Votes:
SELECT count(*) FROM NEWS_VOTES WHERE news_id = (same ID) AND vote = 0
Positive Votes:
SELECT count(*) FROM NEWS_VOTES WHERE news_id = (same ID) AND vote = 1
I need to do this in a single query.
The output on website will be like "This news got 57 positive votes and 67 negative votes."
Thank you.
Ps. I use MYSQL.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
假设赞成票有
vote=1
:assuming positive votes have
vote=1
:试试这个 -
vote = 1 表示投赞成票, vote = 0 表示投反对票。
Try this one -
Where vote = 1 means positive vote, and vote = 0 means negative vote.
选择
(SELECT count(*) FROM NEWS_VOTES WHERE news_id = (same ID) AND vote = 0) Positive_votes,
(SELECT count(*) FROM NEWS_VOTES WHERE news_id = (same ID) AND vote = 1) negative_votes
来自双重;
select
(SELECT count(*) FROM NEWS_VOTES WHERE news_id = (same ID) AND vote = 0) positive_votes,
(SELECT count(*) FROM NEWS_VOTES WHERE news_id = (same ID) AND vote = 1) negative_votes
from dual;