1
我有2個表(用戶和信息)。 我需要選擇所有用戶數據和相關的最後插入 '信息文本'(insert_time)MySql左加入子選擇
表用戶
+----+--------+----------+
| 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 |
+----+--------+----------+----------+
添加GROUP BY,做最大的信息文本。 – jarlh