简体   繁体   English

在子查询中引用外部查询

[英]Referencing outer query in subquery

I have the following query, which generally works, and is supposed to return all rows covering the define timeframe (taking the closest prior and next rows if no absolut match - outlined at http://www.orafaq.com/node/1834 ) 我有以下查询,通常可以工作,并且应该返回覆盖定义时间范围的所有行(如果没有绝对匹配则采用最接近的前一行和下一行 - 在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`

but was hoping to reduce the two table subselects by referencing to the outer select, but obviously it doesnt like it 但希望通过引用外部选择减少两个表子选择,但显然它不喜欢它

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`

Is there a way to have the query without the three table selects? 有没有办法在没有三个表选择的情况下进行查询?

You can do something like this with a join: 您可以通过联接执行以下操作:

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;

I'm not a MySQL expert, so apologies if a bit of syntax tweaking is needed. 我不是MySQL专家,如果需要进行一些语法调整,请为此道歉。

Update: the OP also found this very nice solution . 更新: OP也发现了这个非常好的解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM