Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在MySql中针对每个id只获取一行_Mysql_Sql - Fatal编程技术网

如何在MySql中针对每个id只获取一行

如何在MySql中针对每个id只获取一行,mysql,sql,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

我有两张桌子:

表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中
备注
接受的行,最早的一行基于
日期2
):

但当我使用此查询时,我会通过join返回所有带有备注的数据:

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

使用aggregate
min,max
函数,正如您所说的,您希望date2中的min,所以我更改了

select t1.ID, min(t1.Date1) as date1 ,min(t2.Date2) as date2 ,t2.Remarks from
Table1 t1
inner join Table2 t2 on t1.ID=t2.ID
where t2.Remarks='Accepted'
group by t1.ID,t2.Remarks

使用aggregate
min,max
函数,正如您所说的,您希望date2中的min,所以我更改了

select t1.ID, min(t1.Date1) as date1 ,min(t2.Date2) as date2 ,t2.Remarks from
Table1 t1
inner join Table2 t2 on t1.ID=t2.ID
where t2.Remarks='Accepted'
group by t1.ID,t2.Remarks

只需将GROUPBY和min添加到查询中即可

min (date)
group by t1.ID

只需将GROUPBY和min添加到查询中即可

min (date)
group by t1.ID
我想你想要:

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'
                );
我想你想要:

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'
                );

G-2 2018-08-02 18:07:22 2018-08-04 18:07:07接受
这是一个正确的输出吗?
G-2 2018-08-02 18:07:22 2018-08-04 18:07:07接受
这是一个正确的输出吗?Date2将是
Min
,如果我想获取最早的值??获取错误
列“t1.Date1”必须出现在Group By子句中或用于聚合函数中
请使用我的答案,因为我已经将t.date1放入聚合函数@JupiterDate2将是
Min
,如果我想获取最早的值??获取错误
列“t1.date1”必须出现在Group By子句中或用于聚合函数中请使用我的答案,因为我已经将t.date1放入聚合函数@Jupiter中