Mysql SQL-与自身连接

Mysql SQL-与自身连接,mysql,sql,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

我有一个表
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  |
 -----------------------------
我想从
t1
中获取
abc3
,然后在同一个表
t1
中查找
abc3
日期-1的值,并显示这两条记录

在这种情况下,将有2条记录:

-------------------------------
| date      | id   |  value   |
-------------------------------
| 2/28/2019 |  3   |  abc3    |
| 2/27/2019 |  3   |  abc3    |
-------------------------------
如何做到这一点? 谢谢。

您可以使用:

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) 
  )
请参阅。

您可以使用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) 
  )
请参阅。

这是您想要的吗

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) 
             );
这是你想要的吗

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

你尝试过什么吗???使用自连接,就像你在问题标题中所说的。看起来你已经知道解决方案,自连接。您可能正在搜索用于执行日期算术的函数?您知道如果它们位于不同的表中,您将如何执行该操作吗?使用相同的方法,只是表名相同。@jspcal请推荐ANSI联接。交叉积被认为是过时的。你尝试过什么吗???使用自连接,就像你在问题标题中所说的。看起来你已经知道解决方案,自连接。您可能正在搜索用于执行日期算术的函数?您知道如果它们位于不同的表中,您将如何执行该操作吗?使用相同的方法,只是表名相同。@jspcal请推荐ANSI联接。交叉积被认为是过时的。