[英]UPDATE column values of a table based on no child rows in another table
I have an "items" table:我有一个“项目”表:
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
and an "bids" table:和“出价”表:
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
The item_id column in the bids table is the child of item_id in the items table. bids 表中的 item_id 列是 items 表中 item_id 的子项。
I need to figure out an UPDATE query that does one of two things:我需要找出一个执行以下两件事之一的 UPDATE 查询:
So given the data in the two tables above and today's date of 4/4/14, the results of the update query I need would:因此,鉴于上面两个表中的数据和今天 4/4/14 的日期,我需要的更新查询的结果将:
Anyway, I'm having trouble trying to figure out the proper query.无论如何,我在尝试找出正确的查询时遇到了麻烦。 Any help would be greatly appreciated.
任何帮助将不胜感激。 Thanks for taking the time.
感谢您抽出宝贵的时间。
Best, Josh最好的,乔希
Both parts together.两部分一起。
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();
Here is what I did:这是我所做的:
1.Adds 7 days to expiration if the item is expired (expiration < NOW()) and there are no bids for it in the bids table. 1.如果商品已过期(过期 < NOW())且竞价表中没有竞价,则将过期时间增加 7 天。
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) );
2.Or updates the item's status to sold if the item is expired and there are bids for it in the bids table. 2.或者,如果商品已过期并且投标表中有投标,则将商品的状态更新为已售出。
update items set status = "sold" where expiration < now()
and 0 < (select count(*) from bids where bids.item_id = items.item_id and isnull(withdrawn) );
Part I:第一部分:
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)
Part II:第二部分:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.