0

我有两张桌子:

 question(qid int,title varchar(100))

 answer(aid int,qid int,vote int,content varchar(4096))

Qid 和aid 是主键。

每个问题都有一些答案,每个答案都有一个投票数。

现在采取一些问题qid,如果问题有一些答案,如何找到每个问题的最大(投票)答案?

前任:

mysql> select * from question;
+-----+-------+
| qid | title |
+-----+-------+
|   1 | abc   |
|   2 | efg   |
|   3 | hij   |
|   4 | mn    |
+-----+-------+

mysql> select * from answer;
+-----+------+------+---------+
| aid | qid  | vote | content |
+-----+------+------+---------+
|  77 |    3 |   45 | mysql2  |
| 110 |    1 |   95 | good    |
| 122 |    1 |   78 | bad     |
| 123 |    1 |   34 | bad2    |
| 223 |    2 |   56 | book1   |
| 224 |    2 |   82 | book2   |
+-----+------+------+---------+

现在,给定 qid(1,2),我想找到以下结果:

+-----+------+------+---------+
| aid | qid  | vote | content |
+-----+------+------+---------+
| 110 |    1 |   95 | good    |
| 224 |    2 |   82 | book2   |
+-----+------+------+---------+

我想要完整的答案记录(包含所有列),而不仅仅是 max(vote) 列。

我只想为每个问题显示最佳答案(最大投票答案)。

MySQL 中最好的 SQL 是什么?

谢谢!


2013/1/7 更新:

如果存在,我想展示唯一一个最好answer的(最大投票答案)。@Brian Hoover 的答案仅在 MySQL 下工作正常。

也许没有一个 SQL 在所有数据库下都能正常工作。

4

5 回答 5

1

这是一种方法。

SELECT answer.aid, answer.qid, answer.vote, answer.content
   FROM answer
   JOIN (
          SELECT qid, max(vote) vote FROM answer
          GROUP BY qid) AS max_answer
    ON answer.qid = max_answer.qid AND answer.vote = max_answer.vote
   where answer.qid in (1,2)
   GROUP BY answer.qid, answer.vote

SQL小提琴

在这种情况下,平局将被打破,几乎是随机的,因此每个 questionID 只会显示一条记录,但不能保证在平局的情况下选择的答案是一致的

于 2013-01-05T15:19:14.060 回答
1
SELECT a.* FROM answer a
INNER JOIN (
  SELECT qid, MAX(vote) AS max_vote
  FROM answer
  WHERE qid IN (1,2)
  GROUP BY qid) b
  ON a.qid = b.qid
  AND a.vote = b.max_vote

SQL小提琴

于 2013-01-05T15:20:21.783 回答
0

我认为这可以满足您的要求:

select a.*
from answer a
where a.qid in (1, 2) and
      a.vote = (select max(vote) from answer a2 where a2.qid = a.qid)

此版本适用于任何数据库。在标准 SQL 中还有其他表达方式:

select a.*
from answer a join
     (select a.qid, max(vote) as maxvote
      from answer a
      where a.qid in (1, 2)
      group by a.qid
     ) asum
     on a.qid = asum.qid and a.vote = asum.maxvote

请注意,我将where限制放在子查询中。否则,查询将需要对答案中的所有行进行分组,然后加入,然后进行过滤。

于 2013-01-05T15:14:55.887 回答
0

请尝试以下查询:

select aid,qid,max(vote),content
from
(select a.aid aid,a.qid qid,a.vote vote,a.content content 
from question q join
answer a
on (a.qid = q.qid)
order by 3 desc) tbl
group by qid;
于 2013-01-05T15:16:35.497 回答
0
select * from (
  select qid, aid ,vote
  from answers where qid  in ( 123, 456 ) 
  order by vote desc 
) aaa
group by qid

如果某些记录具有相同的投票,这也可以。

于 2013-01-05T15:59:44.313 回答