当前位置:Gxlcms > mysql > mysql的交集与差集_MySQL

mysql的交集与差集_MySQL

时间:2021-07-01 10:21:17 帮助过:14人阅读

在论坛看到的一个问题这里总结下:

CREATE TABLE consume (
id VARCHAR(11) NOT NULL,
tid VARCHAR(11) NOT NULL
)
COLLATE=’utf8_general_ci’
ENGINE=MyISAM
;
INSERT INTO consume (id, tid) VALUES (‘1’, ‘11’);
INSERT INTO consume (id, tid) VALUES (‘2’, ‘14’);
INSERT INTO consume (id, tid) VALUES (‘3’, ‘12’);

CREATE TABLE teacher (
id VARCHAR(11) NOT NULL,
tname VARCHAR(11) NOT NULL,
tdate DATETIME NOT NULL
)
COLLATE=’utf8_general_ci’
ENGINE=MyISAM
;
INSERT INTO teacher (id, tname, tdate) VALUES (‘10’, ‘李老师’, ‘2008-01-22 21:54:27’);
INSERT INTO teacher (id, tname, tdate) VALUES (‘11’, ‘支老师’, ‘2008-01-21 21:54:27’);
INSERT INTO teacher (id, tname, tdate) VALUES (‘13’, ‘宋老师’, ‘2008-01-28 21:54:27’);
INSERT INTO teacher (id, tname, tdate) VALUES (‘14’, ‘魏老师’, ‘2008-01-29 21:54:27’);
INSERT INTO teacher (id, tname, tdate) VALUES (‘15’, ‘金老师 ‘, ‘2008-01-30 21:54:27’);
INSERT INTO teacher (id, tname, tdate) VALUES (‘16’, ‘赵老师’, ‘2008-01-19 21:54:27’);
INSERT INTO teacher (id, tname, tdate) VALUES (‘17’, ‘张老师’, ‘2008-01-18 21:54:27’);
INSERT INTO teacher (id, tname, tdate) VALUES (‘18’, ‘严老师’, ‘2008-01-17 21:54:27’);
INSERT INTO teacher (id, tname, tdate) VALUES (‘12’, ‘龚老师’, ‘2008-01-25 21:54:27’);
INSERT INTO teacher (id, tname, tdate) VALUES (‘19’, ‘刘老师 ‘, ‘2008-01-17 21:34:27’);


如果teacher中的id在consume中的tid中有,就排在前面,没有就排在后面
对于排在前面的又按照consume中的id升序排
对于排在后面的,按teacher中的tdate的降序排序

对于这个其实分拆出来:
1、teacher中的id在consume中的tid中有按照consume中的id升序排
select t.* from teacher t join consume c on c.tid= t.id order by c.id asc
2、teacher中的id在consume中的tid中没有按teacher中的tdate的降序排序
select t.* from teacher t left join consume c on c.tid= t.id where c.id is NULL order by tdate desc
然后将两张表连起来
select * from (select t.* from teacher t join consume c on c.tid= t.id order by c.id asc)b
union
select * from (select t.* from teacher t left join consume c on c.tid= t.id where c.id is NULL order by tdate desc)a

这里写图片描述
这里说明下2中这个求法
第一张图第二张图
就像这两幅图,从数据看更像第一张图
首先left join 可以找到所有的teacher表的数据(select * from teacher t left join consume c on c.tid= t.id order by tdate desc),如图
这里写图片描述vc7Sw8fWu9Do0qq1xMrHaWTDu9PQyv2+3bXEsr+31qOsy/nS1NTabGVmdCBqb2luILrzvNO49sz1vP5jLmlkIGlzIE5VTEy8tL/JtcO1vdXiuPay7ryvPGJyIC8+DQrA4MvGtdrSu9XFzbw8YnIgLz4NCsTHz9bU2tT10fm1w7W9tdq2/tXFzbyjrNXiwO/G5Mq1ysfSu9H5tcSjrNLyzqpsZWZ0IGpvaW7E3Lm7tcO1vbXEyv2+3crHdGVhY2hlcrHttcTIq7K/yv2+3cjnzbw8YnIgLz4NCjxpbWcgYWx0PQ=="第三张图" src="http://www.bitsCN.com/uploadfile/Collfiles/20150827/20150827100245141.png" title="" />
所以我在剔除掉交集的那部分即可(c.id is not NULL),所以还是在left join 后加个条件c.id is NULL即可得到这个差集类似第二张图
以上是我的交集与差集的理解。

人气教程排行