Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
上下文:PostgreSQL 数据库,带有一个steps包含列subtype和type(整数)的表
steps
subtype
type
需要:如果在新记录插入时列值不等于“4”,则将列值设置subtype为 NULL 。type
这样做的好方法?约束?扳机 ?
谢谢
首先要做的是添加一个约束:
CHECK (type = 4 OR subtype IS NULL) -- if type is 4, sub type may or may not be null -- if type is not 4, sub type must be null
然后,如果您需要,您可以编写一个简单的触发器来设置它,但总的来说,如果有必要,您最好在必要时引发应用程序错误,而不是使用触发器,因为通知应用程序它将得到的不是它保存的通常是一个好的事物。