使用 NOT EXISTS 的 SQL

rad*_*ins 2 sql not-exists

我正在尝试编写一个 SQL 查询,该查询返回自 4 月 1 日以来拥有新发票但尚未安排今年秋季交货的客户的所有学生电子邮件地址。即使我知道有满足这些条件的条目,这也会返回一个空集。我尝试了几种不同的方法,但没有成功,有办法做到这一点吗?

SELECT clients.studentEmail 
FROM `clients`, `invoices` 
WHERE clients.clientId = invoices.clientId 
AND invoices.datePosted > "2013-04-01" 
AND NOT EXISTS 
    (SELECT * 
    FROM appointments, clients
    WHERE clients.clientId = appointments.clientId 
    AND appointments.serviceDirection = "Delivery" 
    AND appointments.date > '2013-07-01')
Run Code Online (Sandbox Code Playgroud)

And*_*mar 5

您必须将not exists子查询与外部查询相关联。例如:

select  clients.studentemail 
from    clients c
join    invoices i
on      c.clientid = i.clientid 
where   invoices.dateposted > "2013-04-01" 
        and not exists 
        (
        select  * 
        from    appointments a
        where   c.clientid = a.clientid -- Relates outer to inner query
                and a.servicedirection = "delivery" 
                and a.date > '2013-07-01')
        )
Run Code Online (Sandbox Code Playgroud)