gpt4 book ai didi

MySql Left Join with subselect

转载 作者:可可西里 更新时间:2023-11-01 07:24:49 24 4
gpt4 key购买 nike

我有 2 个表(用户和信息)。我需要选择所有用户数据和相关的最后插入的“信息文本”(插入时间)

表用户

+----+--------+----------+
| id | name | adress |
+----+--------+----------+
| 1 | Name 1 | Adress 1 |
| 2 | Name 2 | Adress 2 |
| 3 | user 3 | adress 3 |
| 4 | user 4 | adress 4 |
+----+--------+----------+

表格信息

+----+---------+----------+---------------------+
| id | id_user | infotext | insert_time |
+----+---------+----------+---------------------+
| 1 | 1 | info 1 | 2016-11-24 14:03:23 |
| 2 | 1 | info 2. | 2016-11-24 14:08:30 |
| 3 | 3 | text 3. | 2016-11-24 14:08:46 |
+----+---------+----------+---------------------+

我当前的查询是:

SELECT  a.*, b.infotext FROM    user a LEFT JOIN infos b
ON a.id = b.id_user
LEFT JOIN
(
SELECT id_user, MAX(insert_time) newestInsert
FROM infos
GROUP BY id_user
) c ON c.id_user = b.id_user AND
c.newestInsert = b.insert_time

但问题是它输出的 id 不明显:

+----+--------+----------+----------+
| id | name | adress | infotext |
+----+--------+----------+----------+
| 1 | Name 1 | Adress 1 | info 1 |
| 1 | Name 1 | Adress 1 | info 2. |
| 3 | user 3 | adress 3 | text 3. |
| 2 | Name 2 | Adress 2 | NULL |
| 4 | user 4 | adress 4 | NULL |
+----+--------+----------+----------+

我需要的最终结果是:

+----+--------+----------+----------+
| id | name | adress | infotext |
+----+--------+----------+----------+
| 1 | Name 1 | Adress 1 | info 2. |
| 3 | user 3 | adress 3 | text 3. |
| 2 | Name 2 | Adress 2 | NULL |
| 4 | user 4 | adress 4 | NULL |
+----+--------+----------+----------+

最佳答案

将第二个条件放在on 子句中。此方法将其作为相关子查询执行:

SELECT  u.*, i.infotext
FROM user u LEFT JOIN
infos i
ON u.id = i.id_user and
i.insert_time = (SELECT MAX(i2.insert_time)
FROM infos i2
WHERE i2.id_user = i.id_user
);

关于MySql Left Join with subselect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40788108/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com