I have 2 tables :
terminal
id text
1 abc
2 def
3 dfg
termusage
id termid da开发者_JAVA技巧te
1 1 2010-11-01
2 1 2010-10-13
3 2 2010-11-10
4 3 2010-11-13
+ many more records (10 million) approv half are within the date (2010-11-01 and 2010-12-01)
What i want to do is find the terminal.id of the records that do not exist in the termusage table between 2010-11-01 and 2010-12-01
I have looked at select where not exists but nothing is being returned - example
select * from terminal
where not exists (
select * from termusage where date between '2010-11-01' and '2010-12-01' group by termid)
Can anyone please explain how i need to use the where not exists clause or another method !! Cheers
I think that using exists
is a faster solution:
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')
)
Try:
select * from terminal
where id not in (
select termid from usage where date between '2010-11-01' and '2010-12-01')
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'
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`)
The ON
clause indicates how the LEFT JOIN
will be performed, and the _
is a table alias. A table alias is required here.
BTW, what's termusage
.id
for? Do you really need that column?
精彩评论