如何使用mysql从数据库中获取特定行

时间:2018-05-16 06:39:34

标签: mysql

我有下面提到的表格(样本):

ID        Value           Date
TT-12     call rs         2018-04-01 15:18:22
TT-12     srte er         2018-04-02 12:15:18
TT-12     efft rs         2018-04-03 13:04:08
TT-14     efft rs         2018-04-04 17:16:10
TT-14     call rs         2018-04-05 16:25:43
TT-14     srte rs         2018-04-06 21:11:47
TT-18     srte rs         2018-04-07 22:18:34
TT-18     call rs         2018-04-08 07:11:35
TT-18     call rs         2018-04-09 13:07:25

从上表中我只想获取具有值Call rs的行,而不是特定ID的行具有最早的时间。

必需输出:

ID        Value           Date
TT-12     call rs         2018-04-01 15:18:22
TT-14     call rs         2018-04-05 16:25:43
TT-18     call rs         2018-04-08 07:11:35

我正在尝试:select ID,Value,Date from Table1 where ID in ('TT-12','TT-14','TT-18') and order by Value='call rs';

3 个答案:

答案 0 :(得分:0)

试试这个,

select ID, Value, min(Date) as date
from <Table>
where ID in ('TT-12','TT-14','TT-18') and Value = 'call rs'
group by ID, Value

答案 1 :(得分:0)

进行自我加入以获得每ID

最早的行
SELECT 
  a.* 
FROM
  table1 a 
  LEFT JOIN table1 b 
    ON a.ID = b.ID 
    AND a.`Date` > b.`Date` 
    AND b.`Value` = 'call rs' 
WHERE b.ID IS NULL 
  AND a.`Value` = 'call rs' 
  AND a.ID IN ('TT-12', 'TT-14', 'TT-18')

Demo

答案 2 :(得分:0)

select ID,Value,Date from Table1 where Value='call rs' group by ID order by Date desc;