我有一个“项目”表:
item_id | expiration | status
------------------------------------------
1 | 2014-04-02 12:00:00 | NULL
2 | 2014-04-01 17:00:00 | NULL
3 | 2014-03-31 17:30:00 | NULL
4 | 2014-04-14 19:00:00 | NULL
和“出价”表:
bid_id | item_id | withdrawn | amount
---------------------------------------
1 | 1 | NULL | 10
2 | 1 | NULL | 20
3 | 1 | NULL | 30
4 | 2 | 1 | 15
5 | 4 | NULL | 10
出价表中的item_id列是项目表中item_id的子项。
我需要弄清楚UPDATE查询执行以下两项操作之一:
因此,鉴于上述两个表中的数据和今天的4/4/14日期,我需要的更新查询的结果将是:
无论如何,我在试图找出正确的查询时遇到了麻烦。任何帮助将不胜感激。感谢您抽出宝贵时间。
最佳, 约什
答案 0 :(得分:1)
两个部分在一起。
UPDATE items a
LEFT JOIN bids b
ON a.item_id = b.item_id
and b.withdrawn IS NULL
SET a.expiration = CASE WHEN b.bid_id IS NULL
THEN DATE_ADD(a.expiration,INTERVAL 7 DAY)
ELSE a.expiration
END,
a.status = CASE WHEN b.bid_id IS NOT NULL
THEN 'sold'
ELSE a.status
END
WHERE expiration < NOW();
<强> SQL FIDDLE DEMO 强>
答案 1 :(得分:1)
这是我做的:
1.如果商品已过期(到期时间 2.如果商品已过期,并且在出价表中有出价,则将商品的状态更新为已售出。update items set expiration = timestampadd(day, 7, expiration) where expiration < now()
and 0 = (select count(*) from bids where bids.item_id = items.item_id and isnull(withdrawn) );
update items set status = "sold" where expiration < now()
and 0 < (select count(*) from bids where bids.item_id = items.item_id and isnull(withdrawn) );
答案 2 :(得分:0)
第一部分:
UPDATE I
SET expiration = DATE_ADD(I.expiration,INTERVAL 7 DAY)
FROM Items AS I
WHERE I.expiration < NOW()
AND NOT EXISTS(SELECT * FROM Bids AS B WHERE B.item_id = I.item_id AND B.Withdrawn IS NULL)
第二部分:
UPDATE I
SET Status = 'Sold'
FROM Items AS I
WHERE I.expiration < NOW()
AND EXISTS(SELECT * FROM Bids AS B WHERE B.item_id = I.item_id AND B.withdraw IS NULL)