小编典典

在子查询中引用外部查询

sql

我有以下查询,该查询通常可以正常工作,并且应该返回涵盖定义时间范围的所有行(如果没有绝对匹配,则采用最接近的前一行和后一行-在http://www.orafaq.com/node/1834中概述)

SELECT * FROM table
  WHERE id=__ID__ AND `date` BETWEEN 
    IFNULL((SELECT MAX(`date`) FROM table WHERE id=__ID__ AND `date`<=__LOWERLIMIT__), 0)
  AND
    IFNULL((SELECT MIN(`date`) FROM table WHERE id=__ID__ AND `date`>=__UPPERLIMIT__), UNIX_TIMESTAMP())
ORDER BY `date`

但是希望通过引用外部选择来减少两个表的子选择,但是显然它不喜欢它

SELECT * FROM (SELECT * FROM table WHERE id=__ID__) b
  WHERE `date` BETWEEN 
    IFNULL((SELECT MAX(`date`) FROM b WHERE `date`<=__LOWERLIMIT__), 0)
  AND
    IFNULL((SELECT MIN(`date`) FROM b WHERE `date`>=__UPPERLIMIT__), UNIX_TIMESTAMP())
ORDER BY `date`

有没有一种方法可以使查询不选择三个表?


阅读 470

收藏
2021-03-08

共1个答案

小编典典

您可以通过联接执行以下操作:

select * from table a
    inner join (
       select id,
              max(
                  if(`date` <= __LOWERLIMIT__ ,`date`, 0)
              ) as min_date,              
              min(
                 if(`date` >= __UPPERLIMIT__ , `date`, UNIX_TIMESTAMP())
              ) as max_date
           from table
           where id = __ID__
           group by id
    ) range on
    range.id = a.id and
    a.`date` between min_date and max_date;

我不是MySQL专家,因此如果需要一些语法调整,我们深表歉意。

更新: OP也发现了这个非常好的解决方案。

  (select * from t where date < start_date order by date desc limit 1)
  union (select * FROM t WHERE date between start_date and end_date)
  union (select * from t where date > end_date order by date asc limit 1)
2021-03-08