我正在尝试将table2中的最后一个水果计数追加到table1上的查询。
table1 table2
+--------+--------+-------+-----+ +--------+------+-------+
| fruit | season | carbs | fat | | fruit | date | count |
+--------+------+---------+-----+ +--------+------+-------+
| apple | summer | 21 | 0 | | apple | 2015 | 700 |
| banana | all yr | 27 | 0 | | apple | 2014 | 500 |
+--------+--------+-------+-----+ | banana | 2014 | 200 |
| banana | 2013 | 300 |
+--------+------+-------+
goal:
+--------+--------+-------+-----+------------+
| fruit | season | carbs | fat | last_count |
+--------+------+---------+-----+------------+
| apple | summer | 21 | 0 | 700 |
| banana | all yr | 27 | 0 | 200 |
+--------+--------+-------+-----+------------+
我能想到的就是这样(不工作):
SELECT t1.*, t2.count AS last_count FROM table1 AS t1
INNER JOIN
(SELECT fruit, count FROM table2 ORDER BY date DESC) t2 ON t1.fruit = t2.fruit
此外,我应该能够根据table1中的值过滤结果(例如WHERE t1.carbs < 25
)
答案 0 :(得分:0)
解决此问题的一种方法是将table1
加入table2
两次。第一个连接是具有计数的完整table2
,第二个连接是table2
的子查询,其中仅包含每个水果的最新水果记录。
SELECT t1.*, t2.count AS last_count
FROM table1 t1
INNER JOIN table2 t2
ON t1.fruit = t2.fruit
INNER JOIN
(
SELECT fruit, MAX(date) AS date
FROM table2
GROUP BY fruit
) t3
ON t2.fruit = t3.fruit AND
t2.date = t3.date