使用不存在而不是不存在

时间:2016-02-03 22:29:11

标签: mysql sql oracle-sqldeveloper

我有以下查询,它给出了正确的结果,但我想使用不存在而不是不存在。

 select cust_name from customer 
 where cust_id not in
    (select cust_id from ord where ord_id in
        (select ord_id from orderitem where prod_id in
            (select prod_id from product 
             WHERE PROD_DESCRIP = 'Guide to Tennis')))

此外我尝试过 -

select cust_name from customer
where cust_id not exists
    (select cust_id from ord where ord_id in
        (select ord_id from orderitem where prod_id in
            (select prod_id from product
             WHERE PROD_DESCRIP = 'Guide to Tennis')))

我不确定这是否属实

1 个答案:

答案 0 :(得分:1)

您没有将列名放在NOT EXISTS之前,它只是WHERE NOT EXISTS (subquery)

然后,您需要将其作为相关子查询,将外表中的cust_id与内表中的cust_id进行比较。

select cust_name
from customer AS c
where not exists
    (select 1 
     from ord AS o
     where ord_id in
        (select ord_id from orderitem where prod_id in
            (select prod_id from product WHERE PROD_DESCRIP = 'Guide to Tennis'))
        and o.cust_id = c.cust_id)

一般来说,最好使用JOIN而不是WHERE xxx IN - MySQL倾向于更好地优化它。

select cust_name
from customer AS c
where not exists
    (select 1 
     from ord AS o
     join orderitem AS oi ON o.ord_id = oi.ord_id
     join product AS p ON oi.prod_id = p.prod_id
     where p.prod_descrip = 'Guide to Tennis'
        and o.cust_id = c.cust_id)

您可以使用NOT EXISTS模式执行LEFT JOIN

select cust_name
from customer AS c
left join ord AS o ON o.cust_id = c.cust_id
left join orderitem AS oi ON o.ord_id = oi.ord_id
left join product AS p ON oi.prod_id = p.prod_id AND p.prod_descrip = 'Guide to Tennis'
where o.cust_id IS NULL