1

type2 つの単語のうちの 1 つを保持するという列を持つテーブルがある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

オプトの例

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 に答える