我有以下两个表:
T1
+----+------+-----+
| id | name | age |
+----+------+-----+
| 1 | bob | 42 |
| 2 | dave | 12 |
| 3 | mary | 78 |
| 4 | kim | 41 |
+----+------+-----+
T2
+----+-------+------------------+
| id | t1_id | date |
+----+-------+------------------+
| 1 | 1 | 12/26/2014 14:32 |
| 2 | 1 | 12/26/2014 16:32 |
| 3 | 1 | 12/27/2014 14:32 |
| 4 | 2 | 12/26/2014 15:32 |
| 5 | 4 | 12/26/2014 14:32 |
| 6 | 4 | 12/27/2014 14:32 |
+----+-------+------------------+
我希望获得以下结果(仅包括t2中最新的JOINed日期):
+----+------+-----+------------------+
| id | name | age | date |
+----+------+-----+------------------+
| 1 | bob | 42 | 12/27/2014 14:32 |
| 2 | dave | 12 | 12/26/2014 15:32 |
| 3 | mary | 78 | null |
| 4 | kim | 41 | 12/27/2014 14:32 |
+----+------+-----+------------------+
以下内容让我接近,但是从t2加入所有比赛。我如何只包括最新的?
SELECT t1.id, t1,name, t1.age, t2.date
FROM t1
LEFT OUTER JOIN t2 ON t2.t1_id=t1.id;
答案 0 :(得分:2)
mysql> SELECT t1.id, t1.name, t1.age, t3.max_date
FROM t1 LEFT JOIN
(SELECT t1_id, MAX(date) AS max_date FROM t2 GROUP BY t1_id) t3
ON t1.id = t3.t1_id;
产量
+------+------+------+------------------+
| id | name | age | max_date |
+------+------+------+------------------+
| 1 | bob | 42 | 12/27/2014 14:32 |
| 2 | dave | 12 | 12/26/2014 15:32 |
| 3 | mary | 78 | NULL |
| 4 | kim | 41 | 12/27/2014 14:32 |
+------+------+------+------------------+
4 rows in set (0.00 sec)
答案 1 :(得分:2)
只需使用group by
和max()
:
SELECT t1.id, t1.name, t1.age, MAX(t2.date) as date
FROM t1 LEFT OUTER JOIN
t2
ON t2.t1_id = t1.id
GROUP BY t1.id, t1.name, t1.age;
编辑:
您可能会发现这更方便,并且可以获得更好的性能:
SELECT t1.*,
(SELECT MAX(t2.date)
FROM t2
WHERE t2.t1_id = t1.id
) as date
FROM t1;
为获得最佳性能,您需要t2(t1_id, date)
上的索引。