什么Mysql查询将返回此结果?

时间:2010-05-29 22:49:58

标签: sql mysql

我有两个表A,B彼此相关(简化):

A:
+-------+---------+ 
| id    | type    | 
+-------+---------+ 
| 1     | apple   | 
| 2     | orange  | 
| 3     | banana  | 
+-------+---------+ 

B:
+-------+---------+-----------+ 
| id    | a_id    |  rank     |  
+-------+---------+-----------+  
| 1     | 1       |  9.9      |
| 2     | 1       |  7.7      |
| 3     | 2       |  3.3      |
| 4     | 2       |  8.8      |
| 5     | 2       |  1.1      |  
| 6     | 3       |  3.3      |
| 7     | 3       |  2.2      | 
| 8     | 1       |  0.0      | 
+-------+---------+-----------+   

什么mysql查询会返回以下结果?

Result
+-------+---------+-----------+ 
| id    | type    |  rank     |  
+-------+---------+-----------+  
| 1     | apple   |  0.0      | 
| 2     | orange  |  1.1      | 
| 3     | banana  |  2.2      | 
+-------+---------+-----------+ 

选择表B中最后插入的等级( MAX(等级))。

需要从具有最高id的表B中选择结果表中的排名。

3 个答案:

答案 0 :(得分:6)

更新

您可能想尝试加入子查询,以获取MAX(id)中每个a_id的{​​{1}},然后使用table_b INNER JOIN获取排名:

table_b

测试用例:

SELECT   ta.id, 
         ta.type,
         tb.rank
FROM     table_a ta
JOIN     (
            SELECT   MAX(id) AS id, 
                     a_id
            FROM     table_b
            GROUP BY a_id
         ) sub_q ON (sub_q.a_id = ta.id)
JOIN     table_b tb ON (tb.id = sub_q.id)
ORDER BY ta.id;

结果:

CREATE TABLE table_a (id int, type varchar(10));
CREATE TABLE table_b (id int, a_id int, rank decimal(2,1));

INSERT INTO table_a VALUES (1, 'apple');
INSERT INTO table_a VALUES (2, 'orange');
INSERT INTO table_a VALUES (3, 'banana');

INSERT INTO table_b VALUES (1, 1, 9.9);      
INSERT INTO table_b VALUES (2, 1, 7.7);       
INSERT INTO table_b VALUES (3, 2, 3.3);       
INSERT INTO table_b VALUES (4, 2, 8.8);      
INSERT INTO table_b VALUES (5, 2, 1.1);         
INSERT INTO table_b VALUES (6, 3, 3.3);       
INSERT INTO table_b VALUES (7, 3, 2.2);       
INSERT INTO table_b VALUES (8, 1, 0.0);      

答案 1 :(得分:2)

这个怎么样:

SELECT a.id, a.type, b.rank 
FROM tempa a, tempb b 
WHERE a.id = b.a_id 
  AND b.id = (
    SELECT MAX(b.id) 
    FROM tempb b 
    WHERE b.a_id = a.id
)
ORDER BY a.id;

输出:

1, apple, 9.50
2, orange, 1.10
3, banana, 5.50

答案 2 :(得分:2)

SELECT a.id,
       a.type,
       b1.rank
 FROM a,
      b b1
 WHERE b1.a_id = a.id
 AND NOT EXISTS( SELECT b2.id
                  FROM b AS b2
                 WHERE b2.a_id = a.id
                   AND b2.id > b1.id
               )
 ORDER BY a.type