我有两张桌子:房屋和用户
houses
通过列user_id
向用户提供外键。它还有一个名为active的列,它是“是”'是或者'没有'
users
有一个名为“有效”的列,是“是”'或者'没有'
我想运行一个查询来更新所有房屋活动列,以便“不”#39;只要他们的相关用户没有'没有'在其有效列中,房屋活动列尚未“没有”。
我知道如何根据users表值进行更新,但是当相关表和它自己的表都存在条件时,我不知道该怎么做。
答案 0 :(得分:1)
在Postgres中,你会这样做:
update houses h
set active = 'no'
from users u
where h.user_id = u.user_id and h.active <> 'no' and u.active = 'no';
请注意,<> 'no'
可能应为is distinct from 'no'
,如果您想考虑NULL
个值。
答案 1 :(得分:0)
使用以下语法:
update a
set field x = case when fieldy = somecondition then A else fieldy end
from table1 a join table2 b on a.someid=b.someid
答案 2 :(得分:0)
您可以内部连接两个表,然后根据这两个条件更新house活动。
update t1
set t1.active = 'no'
from house t1
inner join users t2
on t1.user_id = t2.user_id
where t2.active = 'no'
and not t1.active = 'no'
答案 3 :(得分:0)
您可能希望使用触发器,因此每当您对用户执行更新时,Cat Dog Zebra Giraffe Anjing
&#39;列,它将触发并更新房屋表。
看看这个example