SQL->关系代数
假设我有以下关系:
Branch (branchNo(PK), street, city, postcode)
Staff (staffNo(PK), fName, lName, sex, branchNo(FK))
这对这个问题来说并不重要,但是 PK = 主键 & FK = 外键
我将如何为以下查询编写关系代数:
列出在格拉斯哥工作的所有女性员工的姓名。
我的尝试:
σStaff.sex=F & Branch.city = 格拉斯哥(πfName, lName, sex,branchNo(Staff) x πcity,branchNo(Branch))
我知道我的选择 (σ) 语句(不要与 SELECT 混淆)在语法上不正确:
σStaff.sex=F & Branch.city = Glasgow
How do I write 关于不同关系的两个选择?或者换句话说,如何在关系代数的 WHERE 子句中表达具有两个或多个条件的 SQL 语句?我已经使用了“&”但这不可能吧?我是否必须将一个选择嵌入到另一个选择中?
不是家庭作业
Suppose I have the following relations:
Branch (branchNo(PK), street, city, postcode)
Staff (staffNo(PK), fName, lName, sex, branchNo(FK))
Not that it matters for this question, but PK = primary key & FK = foreign key
How would I write the relational algebra for the following query:
List the names of all female staff that work in Glasgow.
My attempt:
σStaff.sex=F & Branch.city = Glasgow(πfName, lName, sex, branchNo(Staff) x πcity, branchNo(Branch))
I know that my selection (σ) statement (NOT TO BE CONFUSED WITH SELECT) is syntactically incorrect:
σStaff.sex=F & Branch.city = Glasgow
How do I write two selections on different relations? Or in other words, how do I express an SQL statement with two or more conditions in the WHERE clause in relational algebra? I have used '&' but this cannot be right? Do I have to embed one selection within the other?
NOT HOMEWORK
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
形式关系代数使用逻辑连接和析取 和(通常)相同的符号 ( ∧ 和 ∨,分别),但作者可以自由选择自己的语法。查询可以写为:
πfName, lName(σ(gender=F ∧ city=Glasgow)(Staff ⋈ Branch))
x(更确切地说,⨯)是笛卡尔积的符号。对于自然连接,您需要 ⋈(领结)。
如果您想要笛卡尔积而不是自然连接,您基本上可以通过向选择添加适当的条件来实现自然连接。您还需要处理属性branchNo对于两种关系都是通用的这一事实,您可以通过使用重命名运算符 (ρ)。
πfName, lName(σ(性别=F ∧ 城市=格拉斯哥 ∧ 分支号=bNum)(人员 ⨯ ρbNum/分支号 (分支)))
正式地,您可以这样做,因为:
R ⋈ S = πα(R),α(S)-α(R)(σα(R)∩α(S)=t1..k(R ⨯ ρ t1..k/α(R )∩α(S)(S))))
其中 α(T) 是关系 T 的属性名称(使 α(R) ∩ α(S) 成为公共属性名称),t 1..k ⊈ α(R) ∪ α(S) 是公共属性的新名称。
Formal relational algebra uses logical conjunction and disjunction and (typically) the symbols for same (∧ and ∨, respectively), though authors are free to pick their own syntax. The query could be written as:
πfName, lName(σ(gender=F ∧ city=Glasgow)(Staff ⋈ Branch))
Note that x (rather, ⨯) is the symbol for Cartesian product. For natural joins, you want ⋈ (bowtie).
If you want the Cartesian product rather than natural join, you basically implement a natural join by adding the appropriate condition to the select. You'll also need to deal with the fact that the attribute branchNo is common to both relations, which you can do by using the rename operator (ρ).
πfName, lName(σ(gender=F ∧ city=Glasgow ∧ branchNo=bNum)(Staff ⨯ ρbNum/branchNo(Branch)))
Formally, you can do this because:
R ⋈ S = πα(R),α(S)-α(R)(σα(R)∩α(S)=t1..k(R ⨯ ρ t1..k/α(R)∩α(S)(S))))
where α(T) are the attribute names for relation T (making α(R) ∩ α(S) the common attribute names) and t1..k ⊈ α(R) ∪ α(S) are new names for the common attributes.