SQL-与自身连接

时间:2019-04-18 21:19:53

标签: mysql sql

我有一个表格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    |
-------------------------------

如何实现? 谢谢。

2 个答案:

答案 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) 
             );