0

我目前正在做以下作业:

CREATE TABLE T_1
(COURSE_NO CHAR(8) PRIMARY KEY,
COURSE_NAME CHAR(50) );

CREATE TABLE T_2
(COURSE_NO CHAR(8),
COURSE_NAME CHAR(50) );

CREATE TABLE T_3
(COURSE_NO CHAR(8),
STUDENT_ID CHAR(15),
GRADE CHAR (2));

INSERT INTO T_1
VALUES
('CS100','Data Structures'),
('CS200','Object Oriented Programming'),
('CS300','Distributed Systems'),
('EE100','Circuit Analysis'),
('EE200','VLSI Design'),
('EE300','Packet Switching Networks');

INSERT INTO T_2
VALUES
('EE100','Circuit Analysis'),
('EE200','VLSI Design'),
('EE300','Packet Switching Networks'),
('MA100','Calculus'),
('MA200','Advanced Calculus'),
('MA300','Number Theory');

INSERT INTO T_3
VALUES
('CS100','150-70-5879','B'),
('CS100','280-90-8766','A'),
('EE100','430-76-6858','B'),
('CS200','720-60-5000','B');

我被要求指定给定的元组:(T1 - T2) union (T2 - T1) Union (T1 intersect T2)。

现在我知道 MySQL 使用或者加入减号运算符,我能够以自己的方式处理每个减号,例如:

SELECT *
FROM T_1
LEFT JOIN T_2
ON T_1.Course_No = T_2.Course_no
WHERE T_2.Course_no IS NULL;

我也可以为 T2 - T1 执行此操作,但在 1 个查询中完成所有操作或如何 (T1-T2) U (T2-T1) 或 (T2-T1) U (T1nT2) 时我迷失了。

有什么帮助吗?

4

2 回答 2

9

T 1 ∖ T 2

T<sub>1</sub> ∖ T<sub>2</sub>

T 2 ∖ T 1

T<sub>2</sub> ∖ T<sub>1</sub>

T 1 ∩ T 2

T<sub>1</sub> ∩ T<sub>2</sub>

因此 (T 1 ∖ T 2 ) ∪ (T 2 ∖ T 1 ) ∪ (T 1 ∩ T 2 ) = T 1 ∪ T 2

T<sub>1</sub> ∪ T<sub>2</sub>

SELECT * FROM T_1 UNION SELECT * FROM T_2

sqlfiddle上查看。

于 2012-10-20T17:59:37.637 回答
3

不是最好的,但非常直观的方式:

q1 = (T1 - T2): (SELECT course_no FROM T_1
                 WHERE course_no NOT IN (SELECT course_no FROM T_2))
q2 = (T2 - T1): same way, change T_1 and T_2
q3 = (T1 intersect T2): (SELECT course_no FROM T_1
                         WHERE course_no IN (SELECT course_no FROM T_2))

answer = q1 union q2 union q3

我们得到以下 sql 查询:

(SELECT course_no FROM T_1 WHERE course_no NOT IN (SELECT course_no FROM T_2))
UNION
(SELECT course_no FROM T_2 WHERE course_no NOT IN (SELECT course_no FROM T_1))
UNION
(SELECT course_no FROM T_1 WHERE course_no IN (SELECT course_no FROM T_2))

T_3 怎么样?

编辑:

T_1 = CS100, CS200, CS300, EE100, EE200, EE300
T_2 = EE100, EE200, EE300, MA100, MA200, MA300

q1 = T_1 - T_2 = CS100, CS200, CS300
q2 = T_2 - T_3 = MA100, MA200, MA300
q3 = T_1 intersect T_2 = EE100, EE200, EE300

answer = q1 union q2 union q3 = CS100, CS200, CS300, MA100, MA200, MA300, EE100, EE200, EE300
于 2012-10-20T17:05:06.827 回答