我有2张桌子(产品和购物车)。商品中的商品为foreign key
。
当我为具有相同外国key(id_cart)
的每个产品生成所有代码时,我需要更新表格购物车中的对应行,但仅当所有具有相同id_cart
的产品已经具有此字段时才填写
我想只用一个查询来做这个。有可能吗?
提前致谢!
答案 0 :(得分:0)
您可以使用update-from 示例
UPDATE dbo.Cart
SET [fieldToUpdate] = p.fieldToUpdate
FROM dbo.Cart c
JOIN dbo.products p ON c.fk = p.fk
WHERE cart.id = c.id
答案 1 :(得分:0)
有几种方法可以做到这一点,例如像update
这样的having
子句:
update cart c set status = 'COMPLETE'
where exists (select 1
from product p where p.id_cart = c.id
having count(1) = count(code))
或merge
声明:
merge into cart c
using (select id_cart
from product
group by id_cart
having count(1) = count(code)) p
on (p.id_cart = c.id)
when matched then update set status = 'COMPLETE'
测试数据:
create table product (id number(3), name varchar2(10), code varchar2(4), id_cart number(3));
insert into product values ( 1, 'pen', 'A', 1 );
insert into product values ( 2, 'pencil', 'X', 1 );
insert into product values ( 3, 'box', null, 2 );
insert into product values ( 4, 'paper', 'Q', 2 );
create table cart (id number(3), status varchar2(10));
insert into cart values (1, null);
insert into cart values (2, null);
结果:
ID STATUS
--- ----------
1 COMPLETE
2