说我有两张桌子:
new_dogs <<---- CONTAINS DOGS SPOTTED TODAY
---------
name
breed
color
location
found_date
dog_locations <<---- CONTAINS A HISTORY OF ALL DOGS EVER SPOTTED
---------------
name
breed
location
from_date
thru_date
new_dogs表中填充了今天发现的狗。说我连续3天在公园里找到了一只名叫max的白色贵宾犬。在第一天,max被插入到公园的dog_locations表中,其中from_date为found_date。
第二天最大值显示仍然在公园,所以不需要做任何事情
第3天最大值不再出现在new_dogs表中(可以称为dogs_found_today表),这意味着他不再在公园。这意味着他在dog_locations中的条目不再有效,所以我想关闭他的thru_date。
我需要做的是更新dog_locations表中存在的狗的thru_date,但是在new_dogs表中不存在并且thru_date为NULL。 thru_date将设置为CURRENT_DATE()
每个dog_location必须是唯一的,主键是(name; breed; location; from_date)
我不知道如何去做这个。
我能够选择dog_locations中的狗,但不能选择像new_dog这样的狗:
SELECT name, breed, location, from_date
FROM dog_locations dl
WHERE NOT EXISTS (SELECT name, breed, location, found_date
FROM new_dogs nd
WHERE (nd.name = dl.name) AND (nd.breed = dl.breed)
AND (nd.location = dl.location)
AND (nd.found_date = dl.from_date));
答案 0 :(得分:1)
UPDATE dog_locations SET thru_date = <actualdate or whichever date>
FROM dog_locations dl
WHERE NOT EXISTS (SELECT name, breed, location, found_date
FROM new_dogs nd
WHERE (nd.name = dl.name) AND (nd.breed = dl.breed)
AND (nd.location = dl.location)
AND (nd.found_date = dl.from_date));
干杯 安雅
但是你应该重新考虑你的数据库设计并遵循LukLeds想法引入一只桌子狗......