首页 > 解决方案 > 如果外键的列设置为 false,Postgres 删除一行

问题描述

我有这样的表1:

模板表:

ID              int    
Name            string 
TemplateGroupID int    

模板组表:

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中选择?

标签: sqlpostgresqlsql-delete

解决方案


你可以使用Postgres 的delete ... from ... using ... where ...语法

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

推荐阅读