如何在TABLE1中选择all并使用TABLE2中的匹配MAX(id)进行连接?

时间:2017-07-22 17:23:09

标签: sql mysqli

我想将TABLE1与TABLE2连接,但只获得TABLE2中最高的id匹配。 TABLE1将始终只有1次出现,而TABLE2将有多次出现,我只想要具有最高id的行。

示例:

TABLE1:

+----+------+
| id | name |
+----+------+
|  1 |   a  |
+----+------+

TABLE2

    +----+-----------+------+-------+-------+
    | id | table1_id | text | user1 | user2 |
    +----+-----------+------+-------+-------+
    |  1 |     1     |  aaa |   1   |   2   |
    +----+-----------+------+-------+-------+
    |  2 |     1     |  bbb |   2   |   1   |
    +----+-----------+------+-------+-------+

这就是我想要的结果:

+-----------+-----------+-----------+------+------+
| table1.id | table2.id | table1_id | text | name |
+-----------+-----------+-----------+------+------+
|     1     |     2     |     1     |  bbb |   a  |
+-----------+-----------+-----------+------+------+

我试过这个:

SELECT * FROM table1 LEFT JOIN table2 ON table1.id = table2.table1_id WHERE user1 = '1' OR user2 = '1'

输出是:

+-----------+-----------+-----------+------+------+
| table1.id | table2.id | table1_id | text | name |
+-----------+-----------+-----------+------+------+
|     1     |     1     |     1     |  aaa |   a  |
+-----------+-----------+-----------+------+------+

但是他给了我在TABLE2中具有最低id的行,并且我想要具有最高id的行。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

一种方法将“最大”条件放在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);
相关问题