我有一张桌子可以在任何特定日期存储一个人的茶水偏好。 ;)
customer_id, tea_preference, date
1 'yes please' 2011-01-01
1 'no thanks' 2011-01-02
我需要在给定的日期范围内找到喜欢茶的客户,例如:
SELECT * FROM customers
WHERE tea_preference = 'yes please'
AND date BETWEEN '2011-01-01' AND '2011-01-03'
现在,该查询将提供一个匹配,但如果客户不喜欢该范围内某个日期的茶,我不希望该客户有任何匹配...
我尝试过自我加入,但要么他们不是答案,要么我做得不对,因为我似乎无法得到我追求的结果集。帮助?!
答案 0 :(得分:1)
也许:
SELECT c1.* FROM customers c1
WHERE c1.tea_preference = 'yes please'
AND c1.date BETWEEN '2011-01-01' AND '2011-01-03'
AND NOT EXISTS
(SELECT c2.* FROM customers c2
WHERE c2.tea_preference = 'no thanks'
AND c2.date BETWEEN '2011-01-01' AND '2011-01-03'
AND c1.custom_id = c2.customer_id)