我目前正在做以下作业:
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)联合(T2 - T1)联合(T1与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)。
任何帮助?
答案 0 :(得分:9)
因此(T 1 ∖T 2 )∪(T 2 ∖T 1 )∪(T 1 ∩T 2 )= T 1 ∪T 2 :
SELECT * FROM T_1 UNION SELECT * FROM T_2
在sqlfiddle上查看。
答案 1 :(得分: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-query:
(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