我正在使用MySQL,但我认为这是一个基本的SQL问题 我不知道还有什么要问,只是举个例子。
说我的表中有这些数据:
id date_time foreign_key key value
1 2010-01-01 00:00:00 1 'temperature' 84
2 2010-01-01 00:00:01 1 'humidity' 34
3 2010-01-01 00:00:02 2 'temperature' 45
4 2010-01-01 00:00:03 2 'humidity' 23
5 2010-01-01 00:00:04 2 'dew_point' 78
6 2010-01-01 00:00:05 3 'temperature' 57
7 2010-01-01 00:00:06 3 'humidity' 41
8 2010-01-01 00:00:07 4 'temperature' 19
9 2010-01-01 00:00:08 4 'humidity' 35
10 2010-01-01 00:00:09 4 'dew_point' 24
11 2010-01-01 00:00:10 1 'temperature' 84
12 2010-01-01 00:00:11 1 'dew_point' 34
13 2010-01-01 00:00:12 2 'temperature' 45
14 2010-01-01 00:00:13 2 'humidity' 23
15 2010-01-01 00:00:14 3 'dew_point' 57
16 2010-01-01 00:00:15 3 'humidity' 41
17 2010-01-01 00:00:16 4 'temperature' 19
18 2010-01-01 00:00:17 4 'dew_point' 24
如何获取单个foreign_key的最新密钥?
例如,假设我想要最近的外键4, 我想要的结果是:
id date_time foreign_key key value
9 2010-01-01 00:00:08 4 'humidity' 35
17 2010-01-01 00:00:16 4 'temperature' 19
18 2010-01-01 00:00:17 4 'dew_point' 24
我将用什么SQL来实现这个结果?
顺便说一句,我意识到这不是大多数人选择存储这类数据的第一种方式,但我有我的理由。即,这些值是彼此分开报告的。
答案 0 :(得分:2)
select m.id, m.date_time, m.foreign_key, m.key, m.value
from (
select foreign_key, key, max(date_time) as MaxDate
from MyTable
group by foreign_key, key
) mm
inner join MyTable m on mm.foreign_key = m.foreign_key
and mm.MaxDate = m.date_time
and mm.key = m.key
答案 1 :(得分:1)
SELECT * FROM table WHERE foreign_key ='4'ORDER BY date_time ASC LIMIT 3;
更新,然后正确的是:
SELECT * FROM `table` WHERE `foreign_key`='4' GROUP BY `key` HAVING `date_time`=MAX(`date_time`) ORDER BY `id`;
答案 2 :(得分:1)
select m.id, m.date_time, m.foreign_key, m.key, m.value
from (
select foreign_key, key, max(date_time) as MaxDate
from MyTable
group by foreign_key, key
) mm
inner join MyTable m on mm.foreign_key=m.foreign_key
and mm.MaxDate = m.date_time and mm.key = m.key
正如我在上面评论过的那样,应该首先获得RedFilter的信用。
答案 3 :(得分:0)
我根据this page的答案找出了答案。查询
SELECT m.id, m.date_time, m.foreign_key, m.key, m.value
FROM MyTable m
LEFT OUTER JOIN MyTable mm
ON (m.foreign_key = mm.foreign_key
AND m.key = mm.key
AND m.date_time < mm.date_time)
WHERE mm.key IS NULL
AND m.foreign_key=4;
完全符合我的需要。即:
+----+---------------------+-------------+-------------+-------+
| id | date_time | foreign_key | key | value |
+----+---------------------+-------------+-------------+-------+
| 9 | 2010-01-01 00:00:08 | 4 | humidity | 35 |
| 17 | 2010-01-01 00:00:16 | 4 | temperature | 19 |
| 18 | 2010-01-01 00:00:17 | 4 | dew_point | 24 |
+----+---------------------+-------------+-------------+-------+
感谢您的回复!