gpt4 book ai didi

Mysql从一张表中查询不同的条件

转载 作者:行者123 更新时间:2023-11-29 07:58:29 25 4
gpt4 key购买 nike

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

    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';

但是这不起作用。我认为我必须将连接与子查询一起使用。

mysql是真的吗?

最佳答案

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

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

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

关于Mysql从一张表中查询不同的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24480100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com