在SQL中的一列中选择具有最高值的行

时间:2017-07-28 00:11:23

标签: sql

在MySQL中,我试图为每个“foreign_id”选择一行。它必须是“time”列中具有最高值的行(其类型为DATETIME)。你能帮我看一下SQL SELECT语句的样子吗?谢谢! 这真的很棒!我已经花了好几个小时才找到解决方案:(

这是我的表:

def __callback(self, response):
    if response:
        print ("Handling JS response: %s", response)

这就是结果应该是这样的:

primary_id | foreign_id | name | time
----------------------------------------------------
1          | 3          | a    | 2017-05-18 01:02:03
2          | 3          | b    | 2017-05-19 01:02:03
3          | 3          | c    | 2017-05-20 01:02:03
4          | 5          | d    | 2017-07-18 01:02:03
5          | 5          | e    | 2017-07-20 01:02:03
6          | 5          | f    | 2017-07-18 01:02:03

我尝试按时间(降序)排序中间结果,然后使用LIMIT 1仅选择第一行。但是像这样,我不能为每个foreign_id获取一行。

另一种尝试是首先按时间(降序)对中间结果进行排序,然后再对GROUP BY foreign_id进行排序。但是GROUP BY语句似乎在之前执行了语句(我收到了带有primary_id 1和4的行,而不是3和5)。

3 个答案:

答案 0 :(得分:0)

试试这个

SELECT DISTINCT *
From my_table A
INNER JOIN (SELECT foreign_id, Max(time) AS time FROM my_table GROUP BY foreign_id) B
ON A.foreign_id = B.foreign_id AND A.time = B.time

答案 1 :(得分:0)

只需添加一些数据样本即可分析特殊情况

CREATE TABLE Table1
    (`primary_id` int, `foreign_id` int, `name` varchar(1), `time` datetime)
;

INSERT INTO Table1
    (`primary_id`, `foreign_id`, `name`, `time`)
VALUES
    (1, 3, 'a', '2017-05-18 01:02:03'),
    (2, 3, 'b', '2017-05-19 01:02:03'),
    (3, 3, 'c', '2017-05-20 01:02:03'),
 (7, 3, 'H', '2017-05-20 01:02:03'),
    (4, 5, 'd', '2017-07-18 01:02:03'),
    (5, 5, 'e', '2017-07-20 01:02:03'),
    (6, 5, 'f', '2017-07-18 01:02:03')
;

http://sqlfiddle.com/#!9/38947b/6

select d.primary_id, d.foreign_id, c.name, d.time
from table1 c inner join (    
select max(b.primary_id) primary_id, a.foreign_id,   a.time  
 from table1 b inner join 
 ( select  foreign_id, max(time) time
from table1
group by foreign_id) a
on a.foreign_id = b.foreign_id and a.time=b.time
group by   a.foreign_id,  a.time  ) d
on c.primary_id=d.primary_id

答案 2 :(得分:0)

在过去的日子里,你会把它编码为一个相关的子查询:     选择 *     从表1 o     WHERE primary_id =(         SELECT min(m.primary_id)FROM Table1 m         在哪里m.time =(             SELECT max(i.time)FROM Table1 i             在哪里o.foreign_id = i.foreign_id             )         )

额外的子查询处理重复的foreign_id&的情况。时间价值。如果您确定每个foreign_id的时间都是唯一的,则可以省略中间子查询。