簡體   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