[英]How do i select all in TABLE1 and join with matching MAX(id) from TABLE2?
I want to join TABLE1 with TABLE2, but only getting the highest id matching in TABLE2.我想将 TABLE1 与 TABLE2 连接起来,但只能在 TABLE2 中获得最高的 id 匹配。 TABLE1 will always only have 1 occurrence, while TABLE2 would have multiple occurrences, and i only want the row with the highest id.
TABLE1 将始终只有 1 次出现,而 TABLE2 将有多次出现,我只想要具有最高 id 的行。
Example:示例:
TABLE1:表1:
+----+------+
| id | name |
+----+------+
| 1 | a |
+----+------+
TABLE2表2
+----+-----------+------+-------+-------+
| id | table1_id | text | user1 | user2 |
+----+-----------+------+-------+-------+
| 1 | 1 | aaa | 1 | 2 |
+----+-----------+------+-------+-------+
| 2 | 1 | bbb | 2 | 1 |
+----+-----------+------+-------+-------+
And this is what i want to get out:这就是我想得到的:
+-----------+-----------+-----------+------+------+
| table1.id | table2.id | table1_id | text | name |
+-----------+-----------+-----------+------+------+
| 1 | 2 | 1 | bbb | a |
+-----------+-----------+-----------+------+------+
I have tried with this:我试过这个:
SELECT * FROM table1 LEFT JOIN table2 ON table1.id = table2.table1_id WHERE user1 = '1' OR user2 = '1'
And the output is:输出是:
+-----------+-----------+-----------+------+------+
| table1.id | table2.id | table1_id | text | name |
+-----------+-----------+-----------+------+------+
| 1 | 1 | 1 | aaa | a |
+-----------+-----------+-----------+------+------+
But his gives me the row with the lowest id in TABLE2, and i want the row with the highest id.但是他给了我 TABLE2 中 ID 最低的行,我想要 ID 最高的行。 How can i do that?
我该怎么做?
One method puts the "maximum" condition in the ON
clause:一种方法将“最大”条件放在
ON
子句中:
SELECT t1.*, t2.*
FROM table1 t1 LEFT JOIN
table2 t2
ON t1.id = t1.table1_id AND
t2.id = (SELECT MAX(tt2.id) FROM table2 tt2 WHERE tt2.table1_id = t2.table1_id)
WHERE 1 IN (t1.user1, t1.user2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.