我有一张INVOICES表:
person_id
price
issue_date
如何选择使用issue_date'2013-07-%'收到发票的人并使用issue_date'2013-09-%'收到发票,但是没有收到issue_date'2013-08-%'的发票?
简单地说:那些在2013年8月没有收到发票但确实收到
之前和之后的发票的人答案 0 :(得分:0)
2013年8月没有收到发票但确实收到
之前和之后的发票的人
这应该可以解决问题:
select distinct(person_id)
from INVOICES where
person_id IN
( SELECT person_id from INVOICES where issue_date like '2013-07-%' OR issue_date like '2013-09-%' )
AND person_id NOT IN
(SELECT person_id from INVOICES where issue_date like '2013-08-%')
答案 1 :(得分:0)
怎么样:
select july.person_id
from (SELECT DISTINCT person_id
FROM INVOICES
WHERE issue_date BETWEEN '2013-07-01' AND '2013-07-31') july
inner join
(SELECT DISTINCT person_id
FROM INVOICES
WHERE issue_date BETWEEN '2013-09-01' AND '2013-09-30') sept
on (july.person_id = sept.person_id)
left join
(SELECT DISTINCT person_id
FROM INVOICES
WHERE issue_date BETWEEN '2013-08-01' AND '2013-08-31') aug
on (july.person_id = aug.person_id)
where aug.person_id is null
这将使所有在7月份发票的人和在9月份开具发票,但8月份没有发票。
此外,它并没有使用IN
和NOT IN
操作,这些操作在MySQL中已经很难实现(或者至少比显式连接更差)。