如何选择一个查询中的列不在其他查询的列之间的记录?

时间:2014-05-23 09:23:18

标签: mysql sql

我需要从QUERY1获取记录,time介于timeFromtimeTo之间来自QUERY2

  1. 如何组合这两个查询?什么是最有效的方式?

  2. 我认为从QUERY2中选择t1 time介于timeFromtimeTo之间的记录会更高效,并且只有在加入之后与t2对,对吗? 如果是,我如何使用一个查询来完成?

  3. 注意 :table t1有大约2百万条记录!

    QUERY1

    SELECT ..., time
    FROM t1, t2
    WHERE t1.time >= t2.starttime
    

    QUERY2

    SELECT timeFrom, timeTto
    FROM (...) t3 RIGHT JOIN 
         (...) t4 ON t3.rownum = t4.rownum
    

1 个答案:

答案 0 :(得分:0)

进行三方联接:

SELECT ...
FROM t1
JOIN t2 ON t1.time >= t2.starttime
JOIN (SELECT timeFrom, timeTo
      FROM (...) t3
      RIGHT JOIN (...) t4 ON t3.rownum = t4.rownum) t5
ON t1.time BETWEEN t5.timeFrom AND t5.timeTo

让查询调度程序找出执行连接的顺序。但如果这不起作用,你可以尝试通过重新排序到子查询来帮助它:

SELECT ...
FROM (SELECT t1.*
      FROM t1
      JOIN (SELECT timeFrom, timeTo
            FROM (...) t3
            RIGHT JOIN (...) t4 ON t3.rownum = t4.rownum) t5
      ON t1.time BETWEEN t5.timeFrom AND t5.timeTo) t1
JOIN t2 ON t1.time >= t2.starttime

另外,请确保您在t1.time上有索引。

对于NOT BETWEEN,您需要使用外连接或不存在查询:

SELECT id, time
FROM myTable t
LEFT JOIN filterTable ft ON t.time BETWEEN ft.fromTime AND ft.toTime
WHERE ft.fromTime IS NULL

SELECT id, time
FROM myTable t
WHERE NOT EXISTS (SELECT * FROM filterTable
                  WHERE t.time BETWEEN fromTime AND toTime)

这类似于您必须用于在表中查找在另一个表中没有匹配行的行的查询。唯一的区别是条件是BETWEEN而不是=

DEMO