不在日期之间的表格中

时间:2011-08-18 12:26:37

标签: mysql

我有两张桌子:

终端

id   text
1    abc
2    def
3    dfg

termusage

id  termid   date
1   1        2010-11-01
2   1        2010-10-13
3   2        2010-11-10
4   3        2010-11-13

+更多记录(1000万)批准的一半在该日期内(2010-11-01和2010-12-01)

我想要做的是找到2010-11-01和2010-12-01之间在termusage表中不存在的记录的terminal.id

我看过select不存在的地方但没有返回任何内容 - 例如

select * from terminal
where not exists (
select * from termusage where date between '2010-11-01' and '2010-12-01' group by termid)

任何人都可以解释我如何使用where not exists子句或其他方法!!干杯

4 个答案:

答案 0 :(得分:0)

尝试:

select * from terminal
    where id not in (
        select termid from usage where date between '2010-11-01' and '2010-12-01')

答案 1 :(得分:0)

SELECT t.id FROM usage u 
    INNER JOIN terminal t ON t.id = u.termid AND u.date NOT BETWEEN '2010-11-01' and '2010-12-01'

答案 2 :(得分:0)

SELECT DISTINCT `terminal`.`id`
  FROM `terminal`
  LEFT JOIN
      (
       SELECT `termid`
         FROM `termusage`
        WHERE `date` BETWEEN "2010-11-01" AND "2010-12-01"
      )
    AS `_` ON (`terminal`.`id` = `_`.`termid`)
 WHERE ISNULL(`_`.`termid`)

ON子句指示LEFT JOIN将如何执行,_是表别名。此处需要表别名。

BTW,termusageid的内容是什么?你真的需要那个专栏吗?

答案 3 :(得分:0)

我认为使用exists是一个更快的解决方案:

select * from terminal t
where not exists (
    select * from termusage tu 
    where (t.id = tu.termid) and (date between '2010-11-01' and '2010-12-01')
)