在两个表中查找最大记录

时间:2013-01-05 14:48:03

标签: mysql sql

我有两张桌子:

 question(qid int,title varchar(100))

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

Qid和援助是主要关键。

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

现在问一些问题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(投票)列。

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

MySQL中最好的SQL是什么?

谢谢!


更新2013/1/7:

如果存在,我想展示唯一最好的answer(最大投票答案)。 @Brian Hoover的回答只能在MySQL下运行。

也许所有数据库都没有SQL工作正常。

5 个答案:

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

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

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

答案 2 :(得分: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限制放在子查询中。否则,查询将需要在answer中的所有行上执行group by,然后加入,然后进行过滤。

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

答案 4 :(得分:0)

select * from (
  select qid, aid ,vote
  from answers where qid  in ( 123, 456 ) 
  order by vote desc 
) aaa
group by qid

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