2017-06-14 69 views
-6

我在前面的问题中得到了这个SQL,但我在解释查询时没有得到任何回应。所以我在这里问。 我刚才的问题:How can i remove the oldest entries in my SQL result?有人可以为我解释这个SQL吗?

select a.id, 
     a.user, 
     a.item_id, 
     a.created 
    from reports as a 
where a.created = (select max(created) 
         from reports as b 
        where a.item_id = b.item_id) 
+3

什么部分你不明白? –

+1

请至少链接到其他问题,所以我们有一些背景! –

+0

我想要它解释 - 部分零件,了解完整查询 –

回答

0

你有一个表称为reports和你提取一个由iduseritem_idcreated字段的表。这个新表格只包含每个不同item_id的最大值为created的行。

这部分提取领域,你想:

select a.id, 
     a.user, 
     a.item_id, 
     a.created 

从表中调用报道(一):

from reports as a 

只能提取满足条件的行:

where a.created = (select max(created) 
         from reports as b 
        where a.item_id = b.item_id) 
+0

你能解释一下情况吗? –

+1

'3','1','19333','2017-06-13 19:26:56' '4','1','19333','2017-06-13 19:29:24'你有相同的item_id,对吗?但两个不同的时间戳,所以你选择最近的一个,最大(创建) – MiloBellano

+2

在上面的@ MiloBellano的例子中,你将有两行具有相同的item_id,所以你的查询将选择具有创建的字段的最大值的行(最近的日期) – user2309843

1

下面的子查询是返回最大创建结果(我认为它是日期列,所以最后创建日期将返回)

select max(created) 
        from reports as b 
       where a.item_id = b.item_id 

根据报告表中的结果创建列匹配该值并返回结果。 以下行与两个表的item_id列匹配。

where a.item_id = b.item_id 
+1

子查询返回每个不同item_id的最大创建结果,而不是全局最大值。 – user2309843

相关问题