选择从1列计数到2列

时间:2013-01-17 20:30:45

标签: mysql select join count group-by

我有一个名为type的列的表,它包含两个单词upvotedownvote中的一个我想要按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

示例opt

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

我可以不执行多个查询而不进行子查询吗?

2 个答案:

答案 0 :(得分:2)

这称为 pivot 。在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

答案 1 :(得分: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