如何在MySql中针对每个ID仅获取一行

时间:2018-08-10 10:17:45

标签: mysql sql

我有这两个表:

表1

ID       Date1
----------------------------
G-1      2018-08-01 23:04:15
G-2      2018-08-02 18:07:22

表2

ID       Date2                   Remarks
-------------------------------------------
G-1      2018-08-01 23:45:45     Rgt RTT
G-1      2018-08-02 19:07:18     AFF XTX
G-1      2018-08-02 21:25:45     Accepted
G-2      2018-08-03 15:03:04     Ref ytt
G-3      2018-08-04 18:07:07     Accepted
G-4      2018-08-05 22:25:45     Accepted

我想要输出((在表2中,行RemarksAccepted,最旧的基于Date2的行):

ID       Date1                 Date2                   Remarks  
----------------------------------------------------------------
G-1      2018-08-01 23:04:15   2018-08-02 21:25:45     Accepted
G-2      2018-08-02 18:07:22   2018-08-04 18:07:07     Accepted

但是当我使用此查询时,我通过join来获取所有带有注释的数据:

select 
    t1.ID, t1.Date1, t2.Date2, t2.Remarks 
from
    Table1
Left join 
    Table2 on t1.ID = t2.ID
where 
    t2.Remarks = 'Accepted';

3 个答案:

答案 0 :(得分:3)

使用聚合items = ["pickle", "tuna", "pasta_sauce", "beans", "soup"] price = [6, 5, 3, 2, 2] hash = {} # or Hash.new items.each_with_index do |var, idx| hash[var] = price[idx] end puts hash["pasta_sauce"] # 3 puts hash["pickle"] # 6 函数,正如您所说的,要在date2中设置最小值,以便我更改

min,max

答案 1 :(得分:1)

我想你想要

select t1.id, t1.date, t2.date, t2.remarks
from table2 t2 join
     table1 t1
     on t2.id = t1.id
where t2.remarks = 'Accepted' and
      t2.date = (select min(tt2.date)
                 from table2 tt2
                 where tt2.id = t2.id and tt2.remarks = 'Accepted'
                );

答案 2 :(得分:-1)

只需在查询中添加分组依据和最小值

min (date)
group by t1.ID