我有一个表格t1
如下
-----------------------------
| date | id | value |
-----------------------------
| 2/28/2019 | 1 | abc1 |
| 2/28/2019 | 2 | abc2 |
| 2/28/2019 | 3 | abc3 |
| 2/27/2019 | 1 | abc4 |
| 2/27/2019 | 2 | abc5 |
| 2/27/2019 | 3 | abc3 |
-----------------------------
我想从abc3
中提取t1
,然后在同一表abc3
中查找date - 1
天的t1
值并显示两条记录。
在这种情况下,它将是2条记录:
-------------------------------
| date | id | value |
-------------------------------
| 2/28/2019 | 3 | abc3 |
| 2/27/2019 | 3 | abc3 |
-------------------------------
如何实现? 谢谢。
答案 0 :(得分:1)
您可以使用EXISTS:
select t.*
from tablename t
where
value = 'abc3'
and
exists (
select 1 from tablename
where value = 'abc3' and date in (t.date - INTERVAL 1 DAY, t.date + INTERVAL 1 DAY)
)
请参见demo。
答案 1 :(得分:1)
这是您想要的吗?
select t.*
from t
where value = 'abc3'
order by date desc
limit 2;
或者,您是否想查找 abc3
,因为该值连续两天都相同?
select t.*
from t
where value = 'abc3' and
exists (select 1
from tablename t2
where t2.value = t.value and
t2.date in (t.date - interval 1 day, t.date + interval 1 day)
);