我有两个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 |
+-------+---------+-----------+
Run Code Online (Sandbox Code Playgroud)
什么mysql查询将返回以下结果?
Result
+-------+---------+-----------+
| id | type | rank |
+-------+---------+-----------+
| 1 | apple | 0.0 |
| 2 | orange | 1.1 |
| 3 | banana | 2.2 |
+-------+---------+-----------+
Run Code Online (Sandbox Code Playgroud)
选择在表B中最后插入的等级(它不是 MAX(等级)).
需要从具有最高id的表B中选择结果表中的排名.
更新
你可能想尝试使用子查询加盟,以获得MAX(id)每个a_id中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;
Run Code Online (Sandbox Code Playgroud)
测试用例:
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);
Run Code Online (Sandbox Code Playgroud)
结果:
+------+--------+------+
| id | type | rank |
+------+--------+------+
| 1 | apple | 0.0 |
| 2 | orange | 1.1 |
| 3 | banana | 2.2 |
+------+--------+------+
3 rows in set (0.01 sec)
Run Code Online (Sandbox Code Playgroud)