没有子查询,这个查询是否可行?

时间:2013-11-19 09:54:39

标签: sql oracle join oracle11g

  

当客户何时将所有客户的信用额度设置为0   他们在2008年和2009年得到了提醒

简化表

Create table customer (id int, credit_limit int);
Create table Bill (id int, customer_id int, date datetime);

我的方法:

Update customer 
   set credit_limit = 0 
where (select customer_id 
       from bills 
       where year(reminder) = 2008) 
  and (select customer_id 
       from bills 
       where year(reminder) = 2009)

4 个答案:

答案 0 :(得分:2)

也许是这样的:

UPDATE customer set credit_limit = 0 
WHERE EXISTS
    (
        SELECT
            NULL
        FROM
            bills
        WHERE
            bills.customer_id=customer.customer_id
            AND year(bills.reminder) IN (2008,2009)
    )

或者,如果您想检查2008年和2009年是否存在。然后就可以了

UPDATE customer set credit_limit = 0 
WHERE EXISTS
    (
        SELECT
            NULL
        FROM
            bills
        WHERE
            bills.customer_id=customer.customer_id
            AND year(reminder) = 2008
    )
    AND EXISTS
    (
        SELECT
            NULL
        FROM
            bills
        WHERE
            bills.customer_id=customer.customer_id
            AND year(reminder) = 2009
    )

答案 1 :(得分:0)

这应该可以解决Oracle的问题:

update
    (
    select
        c.id,
        c.credit_limit,
    from customer c
        inner join Bill b1 on
            c.id = b1.customer_id and year(b1.date) = 2008
        inner join Bill b2 on
            c.id = b2.customer_id and year(b2.date) = 2009

    ) up
set up.credit_limit = 0

答案 2 :(得分:0)

我不认为没有子查询(使用MERGE的可能性 - 但这仍然是类似子查询)。

您可以简化子查询,使其更有效(并且更正确)

update customer 
  set credit_limit = 0
where id in (select customer_id
             from bills 
             where extract(year from reminder) in (2008, 2009)
             group by customer_id
             having count(distinct extract(year from reminder)) = 2)

答案 3 :(得分:-1)

Update customer set credit_limit = 0
Inner join Bill b1 on customer.id = b1.customer_id
join Bill b2 on b1.customer_id = b2.customer_id  and year(b1.reminder) = 2009 and year(b2.reminder) = 2008