繁体   English   中英

从具有不同条件的一张表进行MySQL查询

[英]Mysql query from one table with different conditions

我想计算此表的每个项目的投票数:

    user    item    vote
--------------------------------
    4       1       left
    4       2       left
    2       2       right
    3       2       left
    1       3       right

结果必须是这样的:

item | left_vote | right_vote
1       1               0
2       2               1
3       0               1

我试图使用这样的查询:

SELECT t.item, count(vote) as left_count, t.right_count  from (SELECT count(vote) as right_count, item from view where vote = 'right') as t, view where vote = 'left';

但这是行不通的。 我认为我必须与子查询一起使用join。

mysql是真的吗?

在MySQL中,您可以只使用条件聚合:

select item, sum(vote = 'left') as left_vote, sum(vote = 'right') as right_vote
from votes v
group by item;

您不需要为此的联接或子查询。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM