1

我有一个表,其中有一列称为type它包含两个单词之一,upvote或者downvote我想按 a.question_id 分组,然后得到 2 列,每列计数。

select a.*, u.* from answers a
left join users u using(user_id)
left join vote_history v using(answer_id)
where a.question_id = 4 and deleted < 4
group by v.question_id
order by votes desc

示例选择

ColumnA  | ColumnB  | upvotes | downvotes
---------+----------+---------+----------
record1A | record2B | 3       | 2
record2A | record2B | 2       | 5

我是否可以在不执行多个查询且不执行子查询的情况下执行此操作?

4

2 回答 2

3

这称为枢轴。在 MySQL 中,您可以使用带有CASE表达式的聚合函数将数据转换为列:

select a.*, u.*,
    SUM(case when v.type='upvote' then 1 else 0 end) Upvotes,
    SUM(case when v.type='downvote' then 1 else 0 end) Downvotes,
from answers a
left join users u using(user_id)
left join vote_history v using(answer_id)
where a.question_id = 4 and deleted < 4
group by v.question_id
order by votes desc
于 2013-01-17T20:34:51.707 回答
1

这可以工作:

select 
  a.*, 
  u.*,
  SUM(IF(v.type = 'upvote',1,0) as upvotes,
  SUM(IF(v.type = 'downvote',1,0) as downvotes,
from answers a
left join users u using(user_id)
left join vote_history v using(answer_id)
where a.question_id = 4 and deleted < 4
group by v.question_id
order by votes desc
于 2013-01-17T20:33:38.507 回答