如果外键的列设置为false,则Postgres删除一行

问题描述 投票:1回答:3

我有这样的表1:

模板表:

ID              int    
Name            string 
TemplateGroupID int    

Template_group表:

ID              int    
Name            string 
IsDefault       bool  

如果该行的FK到template_group列IsDefault设置为true,我想删除模板中的一行。我怎样才能做到这一点?我以为是这样的:

delete from template 
where id =33 and exists (
    select * from template_group where is_default = true
);

但是我不认为这是正确的,因为我不必在子选择中选择TemplateGroupId吗?

sql postgresql sql-delete
3个回答
2
投票

您可以使用Postgres' delete ... from ... using ... where ... syntax

delete ... from ... using ... where ...

2
投票

您在WHERE子句中需要另一个条件:

delete 
from template t  
using template_group g 
where g.ID = t.TemplateGroupID and g.IsDefault = true

0
投票

您需要的是此sql:

delete from template t 
where t.id = 33 
and exists (
  select * 
  from template_group 
  where id = t.TemplateGroupID and is_default = true
);

ps:我用辅音写了所有单词,因为即使您写了元音Postgresql也会将它们转换为辅音。

© www.soinside.com 2019 - 2024. All rights reserved.