2016-07-28 31 views
0

只有當滿足條件的行數大於某個值時,纔想在行中插入一個新條目。在sql中放置一個條件,其中sql

我該怎麼做?我的示例sql查詢給出的錯誤是

INSERT INTO coupon_use (coupon, customer) VALUES (3, 4) 
WHERE (SELECT count(redeem_at) from coupon_use WHERE coupon=3) <= 150; 

它告訴我有錯誤在哪裏。我如何糾正這個查詢?

我想在這個表中插入一個項目使用值3和4僅在優惠券的數量有redemed是greator超過150

我的數據庫服務器的Postgres

回答

2

不能使用VALUES和WHERE子句。

你需要一個SELECT

insert into coupon_use(coupon, customer) 
select 3, 4 
from coupon_use 
where coupon = 3 
group by coupon -- we can group by coupon to be able to use an HAVING clause 
having count(redeem_at) <= 150