Constraints and Triggers

news2025/6/7 2:53:00

目录

Kinds of Constraints

Single-Attribute Keys

Multiattribute Key

Foreign Keys

Expressing Foreign Keys

Enforcing Foreign-Key Constraints

Actions Taken

Attribute-Based Checks

Timing of Checks

Tuple-Based Checks

Assertions

Timing of Assertion Checks

Triggers: Motivation

Event-Condition-Action Rules

Preliminary Example: A Trigger


  • A constraint is a relationship among data elements that the DBMS is required to enforce.(约束是数据库系统强制加在数据元素之间的关系)
  • Example: key constraints.

Triggers are only executed when a specified condition occurs(e.g., insertion of a tuple.)

  • Easier to implement than complex constraints.

Kinds of Constraints

  • Keys.

  • Foreign-key, or referential-integrity.

  • Value-based constraints.

  • Constrain values of a particular attribute.

  • Tuple-based constraints.

  • Relationship among components.

  • Assertions: any SQL boolean expression.

Single-Attribute Keys

  • Place PRIMARY KEY or UNIQUE after the type in the declaration of the attribute.

  • Example:

CREATE TABLE Beers (
        name CHAR(20) UNIQUE,
        manf CHAR(20)
);

Multiattribute Key

The bar and beer together are the key for Sells:
CREATE TABLE Sells (
        bar CHAR(20),
        beer VARCHAR(20),
        price REAL,
        PRIMARY KEY (bar, beer)
);

多属性键,使用锁哥属性来标志唯一元组,适用于单属性无法标识的场景

Foreign Keys

  • Values appearing in attributes of one relation must appear together in certain attributes of another relation.(一个关系中的属性必定会出现在其他关系中)

  • Example: in Sells(bar, beer, price), we might expect that a beer value also appears in Beers.name .

Expressing Foreign Keys

Use keyword REFERENCES, either:

  • After an attribute (for one-attribute keys).

  • As an element of the schema:

FOREIGN KEY (<list of attributes>) REFERENCES <relation> (<attributes>)

Referenced attributes must be declared

PRIMARY KEY or UNIQUE

Enforcing Foreign-Key Constraints

If there is a foreign-key constraint from relation R to relation S, two violations are possible:

  • An insert or update to R introduces values not found in S.

  • A deletion or update to S causes some tuples of R to “dangle.”

Actions Taken

  • Default : Reject the modification.(默认情况是拒绝数据修改操作)

  • Cascade : Make the same changes in Sells.(级联检查)

Deleted beer: delete Sells tuple.

Updated beer: change value in Sells.

  • Set NULL : Change the beer to NULL.

Attribute-Based Checks

  • Constraints on the value of a particular attribute.
  • Add CHECK(<condition>) to the declaration for the attribute.
  • The condition may use the name of the attribute, but any other relation or attribute name must be in a subquery.(Checks允许使用多属性,但是如果出现跨表的多属性,其他表中的属性必须使用子查询)

Timing of Checks

Attribute-based checks are performed only when a value for that attribute is inserted or updated.(基于属性的检查只有在数据插入和更新时才触发)

  • Example: CHECK (price <= 5.00) checks every new price and rejects the modification (for that tuple) if the price is more than $5.

  • Example: CHECK (beer IN (SELECT name FROM Beers)) not checked if a beer is deleted from Beers (unlike foreign-keys).(这里可以看出与外键约束的不同,在Beers表中数据被删除时并不会检查这个Checks约束)

Tuple-Based Checks

CHECK (<condition>) may be added as a relation-schema element.

The condition may refer to any attribute of the relation.

But other attributes or relations require a subquery.

Checked on insert or update only

对比维度基于属性的检查(列级约束)基于元组的检查(表级约束)
能否使用本表中的其他属性?❌ 不能直接引用
约束表达式必须仅依赖当前列的值。
✅ 可以直接引用
可在约束条件中使用同一行的其他列(如 CHECK (end_date > start_date))。
能否使用跨表属性?✅ 可以间接使用(需通过子查询)。✅ 可以直接使用(通过子查询)。
如何使用跨表属性?1. 子查询必须独立于当前行
子查询不能引用当前表的其他列,只能依赖固定条件或其他表的数据。
示例
sql<br> CHECK (category_id IN (SELECT category_id FROM Categories))<br>
1. 子查询可结合当前行的属性
子查询可通过 NEW.column(如 MySQL)或直接引用当前行的列。
示例
sql<br> CHECK (salary > (SELECT AVG(salary) FROM Employees WHERE dept_id = NEW.dept_id))<br>
何时触发 CHECK 检查?仅在该列的值被插入或更新时触发
- 若其他列更新,即使整行数据变化,该约束也不会触发。
- 示例:CHECK (price > 0) 仅在 price 列被修改时验证。
仅在整行数据被插入或更新时触发
- 无论哪一列变化,只要行数据发生修改,约束都会验证。
- 示例:CHECK (end_date > start_date) 在插入或更新任意列时均会验证。

Assertions

  • These are database-schema elements, like relations or views.(是一种数据库模式元素)

  • Defined by:

CREATE ASSERTION <name>

CHECK (<condition>);

  • Condition may refer to any relation or attribute in the database schema.(约束条件可以调用数据模式中的所有属性和关系)

Timing of Assertion Checks

  • In principle, we must check every assertion after every modification to any relation of the database.
  • A clever system can observe that only certain changes could cause a given assertion to be violated.

Example: No change to Beers can affect FewBar. Neither can an insertion to Drinkers.

Triggers: Motivation

  • Assertions are powerful, but the DBMS often can’t tell when they need to be checked.

  • Attribute- and tuple-based checks are checked at known times, but are not powerful.

  • Triggers let the user decide when to check for any condition.

断言虽然功能比较强大但是触发的时机不明确,基于属性和元组的检查虽然触发时机比较明确但是逻辑功能比较有限,而触发器就比较好的解决了这两者的缺陷,将优点结合了起来。

Event-Condition-Action Rules

Another name for “trigger” is ECA rule, or event-condition-action rule.

  • Event : typically a type of database modification, e.g., “insert on Sells. ”(一般来说是指数据的修改类型)

  • Condition : Any SQL boolean-valued expression.(SQL语句是触发器被触发的条件)

  • Action : Any SQL statements.(动作,也就是触发器被触发后需要执行的SQL语句)

Preliminary Example: A Trigger

Instead of using a foreign-key constraint and rejecting insertions into Sells(bar, beer, price) with unknown beers, a trigger can add that beer to Beers, with a NULL manufacturer.

Example: Trigger Definition

CREATE TRIGGER BeerTrig
AFTER INSERT ON Sells
REFERENCING NEW ROW AS NewTuple
FOR EACH ROW
WHEN (NewTuple.beer NOT IN
(SELECT name FROM Beers))
INSERT INTO Beers(name)
VALUES(NewTuple.beer);

Options: FOR EACH ROW

Triggers are either “row-level” or “statement-level. ”

  • Row level triggers : execute once for each modified tuple.(行级触发就是变化了几行数据就执行几次触发器)

  • Statement-level triggers : execute once for a SQL statement, regardless of how many tuples are modified.(语句级触发就是一行语句不管多少行数据发生变化,都只执行一次触发器)

Options: REFERENCING

  • INSERT statements imply a new tuple (for row-level) or new table (for statement-level). The “table” is the set of inserted tuples.

  • DELETE implies an old tuple or table.

  • UPDATE implies both.

Refer to these by [NEW OLD][TUPLE TABLE] AS <name>

维度行级触发器(FOR EACH ROW)语句级触发器(FOR EACH STATEMENT)
触发频率每插入 / 更新 / 删除 一行数据 触发一次每执行 一条 SQL 语句 触发一次(无论影响多少行)
数据范围单次触发处理 单行数据单次触发处理 全表数据(语句影响的所有行)
数据形态以 行(元组) 为单位以 临时表(多行集合) 为单位

Options: The Condition

  • Any boolean-valued condition.

  • Evaluated on the database as it would exist before or after the triggering event, depending on whether BEFORE or AFTER is used.

But always before the changes take effect.(不管是after还是before,所有数据库的状态都没有真正的发生变化)

Access the new/old tuple/table through the names in the REFERENCING clause 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2400936.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

BERT:让AI真正“读懂”语言的革命

BERT&#xff1a;让AI真正“读懂”语言的革命 ——图解谷歌神作《BERT: Pre-training of Deep Bidirectional Transformers》 2018年&#xff0c;谷歌AI团队扔出一篇核弹级论文&#xff0c;引爆了整个NLP领域。这个叫BERT的模型在11项任务中屠榜&#xff0c;甚至超越人类表现…

冷雨泉教授团队:新型视觉驱动智能假肢手,拟人化抓握技术突破,助力截肢者重获生活自信

研究背景&#xff1a;日常生活中&#xff0c;健康人依靠手完成对物体的操作。对于手部截肢患者&#xff0c;手部的缺失导致他们难以有效地操作物体&#xff0c;进而影响正常的日常生活。拥有一个能够实现拟人地自然抓取多种日常物体的五指动力假手是手部截肢患者的夙愿&#xf…

pikachu靶场通关笔记14 XSS关卡10-XSS之js输出(五种方法渗透)

目录 一、源码分析 1、进入靶场 2、代码审计 二、渗透实战 1、根据提示输入tmac 2、XSS探测 3、注入Payload1 4、注入Payload2 5、注入Payload3 6、注入Payload4 7、注入Payload5 本系列为通过《pikachu靶场通关笔记》的XSS关卡(共10关&#xff09;渗透集合&#x…

李沐-动手学深度学习:RNN

1.RNN从零开始实现 import math import torch from torch import nn from torch.nn import functional as F from d2l import torch as d2l#8.3.4节 #batch_size&#xff1a;每个小批量中子序列样本的数目&#xff0c;num_steps&#xff1a;每个子序列中预定义的时间步数 #loa…

【教学类-36-10】20250531蝴蝶图案描边,最适合大小(一页1图1图、2图图案不同、2图图案相同对称)

背景说明: 之前做了动物头像扇子(描边20),并制作成一页一套图案对称两张 【教学类-36-09】20250526动物头像扇子的描边(通义万相)对称图40张,根据图片长宽,自动旋转图片,最大化图片-CSDN博客文章浏览阅读1k次,点赞37次,收藏6次。【教学类-36-09】20250526动物头像…

高效DBA的日常运维主题沙龙

2024年11月10日&#xff0c;在宁波组织了高效DBA的日常运维沙龙活动&#xff0c;大概有20人左右现场参加。会议的主题为&#xff1a; 目标&#xff1a; 1、识别高频低效操作并制定自动化方案 2、建立关键运维指标健康度体系 3、输出可立即落地的优化清单 会议议程 一、效能瓶…

AAAI 2025论文分享│STD-PLM:基于预训练语言模型的时空数据预测与补全方法

本文详细介绍了一篇发表于人工智能顶级会议AAAI 2025的论文《STD-PLM: Understanding Both Spatial and Temporal Properties of Spatial-Temporal Data with PLM》。该论文提出了一种基于预训练语言模型&#xff08;Pre-trained Language Model‌&#xff0c;PLM&#xff09;的…

Ethernet/IP转DeviceNet网关:驱动大型矿山自动化升级的核心纽带

在大型矿山自动化系统中&#xff0c;如何高效整合新老设备、打通数据孤岛、实现统一控制&#xff0c;是提升效率与安全的关键挑战。JH-EIP-DVN疆鸿智能EtherNet/IP转DeviceNet网关&#xff0c;正是解决这一难题的核心桥梁&#xff0c;为矿山各环节注入强劲连接力&#xff1a; …

[蓝桥杯]模型染色

模型染色 题目描述 在电影《超能陆战队》中&#xff0c;小宏可以使用他的微型机器人组合成各种各样的形状。 现在他用他的微型机器人拼成了一个大玩具给小朋友们玩。为了更加美观&#xff0c;他决定给玩具染色。 小宏的玩具由 nn 个球型的端点和 mm 段连接这些端点之间的边…

卡西欧模拟器:Windows端功能强大的计算器

引言 大家还记得初中高中时期用的计算器吗&#xff1f;今天给大家分享的就是一款windows端的卡西欧计算器。 软件介绍 大家好&#xff0c;我是逍遥小欢。 CASIO fx-9860G是一款功能强大的图形计算器&#xff0c;适用于数学、科学和工程计算。以下是其主要功能和特点的详细介…

机器学习基础(三) 逻辑回归

目录 逻辑回归的概念核心思想 Sigmoid 函数 逻辑回归的原理和底层优化手段伯努利分布最大似然估计 Maximum Likelihood Estimation &#xff08;MLE&#xff09;伯努利分布的似然函数交叉熵损失函数&#xff08;Cross-Entropy Loss&#xff09;&#xff0c;也称为 对数损失&…

Qwen-3 微调实战:用 Python 和 Unsloth 打造专属 AI 模型

虽然大家都忙着在 DeepSeek 上构建应用&#xff0c;但那些聪明的开发者们却悄悄发现了 Qwen-3 的微调功能&#xff0c;这可是一个隐藏的宝藏&#xff0c;能把通用型 AI 变成你的专属数字专家。 通过这篇文章&#xff0c;你将学到如何针对特定用途微调最新的 Qwen-3 模型。无论…

微软Build 2025:Copilot Studio升级,解锁多智能体协作未来

微软Build 2025大会圆满落幕&#xff0c;作为年度科技盛会&#xff0c;它一直是开发与AI技术突破性创新的重要展示平台。对于工程师、创作者和领域专家来说&#xff0c;这是了解微软生态未来动向的关键时刻。今年&#xff0c;Microsoft Copilot Studio推出了一系列新功能&#…

设计模式——系统数据建模设计

摘要 本文主要介绍了UML在软件系统分析和设计中的应用&#xff0c;详细阐述了六大类关系&#xff08;泛化、实现、依赖、关联、聚合、组合&#xff09;及其在UML类图中的表示方法&#xff0c;并通过具体例子说明了这些关系在实际编程中的应用。同时&#xff0c;文章还概述了UM…

解决docker运行zentao 报错:ln: failed to create symbolic link ‘/opt/zbox/tmp/mysq

1 背景描述 禅道使用docker部署运行过一段&#xff0c;服务正常。 后因服务器断电重启&#xff0c;禅道服务也随docker一起启动&#xff0c;但是服务却无法访问。如下如&#xff1a; 2 查看日志&#xff0c;定位原因 查看禅道日志&#xff1a; # docker logs zentao容器di…

OA工程自动化办公系统 – 免费Java源码

概述 功能完备的OA工程自动化办公系统Java源码&#xff0c;采用主流技术栈开发&#xff0c;无论是学习SpringBoot框架还是开发企业级应用&#xff0c;都是不可多得的优质资源。 主要内容 技术架构 ​​后端技术栈​​&#xff1a; 核心框架&#xff1a;SpringBoot 2.xORM框…

Apache IoTDB V2.0.3 发布|新增元数据导入导出脚本适配表模型功能

Release Announcement Version 2.0.3 Apache IoTDB V2.0.3 已经发布&#xff01; V2.0.3 作为树表双模型正式版本&#xff0c;主要新增元数据导入导出脚本适配表模型、Spark 生态集成&#xff08;表模型&#xff09;、AINode 返回结果新增时间戳&#xff0c;表模型新增部分聚…

某校体育场馆结构自动化监测

1. 项目简介 某小学学校成立于2020年&#xff0c;是一所公办小学&#xff0c;以高起点定位为该区优质教育新增长极&#xff0c;依托当地学院及教师进修学院附属小学资源&#xff0c;注重学生综合素质培养&#xff0c;近年来&#xff0c;该小学聚焦“五育” 领域&#xff0c;不…

Android 3D球形水平圆形旋转,旋转动态更换图片

看效果图 1、事件监听类 OnItemClickListener&#xff1a;3D旋转视图项点击监听器接口 public interface OnItemClickListener {/*** 当旋转视图中的项被点击时调用** param view 被点击的视图对象* param position 被点击项在旋转视图中的位置索引&#xff08;从0开始&a…

数据结构与算法学习笔记(Acwing 提高课)----动态规划·树形DP

数据结构与算法学习笔记----动态规划树形DP author: 明月清了个风 first publish time: 2025.6.4 ps⭐️树形动态规划&#xff08;树形DP&#xff09;是处理树结构问题的一种动态规划方法&#xff0c;特征也很明显&#xff0c;会有一个树形结构&#xff0c;其实是DFS的优化。…