在论坛看到的一个问题这里总结下:
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),如图
这里可以看到我们只需要的是id没有数据的部分,所以在left join 后加个条件c.id is NULL即可得到这个差集
类似第一张图
那现在怎样得到第二张图,这里其实是一样的,因为left join能够得到的数据是teacher表的全部数据如图
所以我在剔除掉交集的那部分即可(c.id is not NULL),所以还是在left join 后加个条件c.id is NULL即可得到这个差集类似第二张图
以上是我的交集与差集的理解。
参考:http://blog.itpub.net/29510932/viewspace-1777673/
http://blog.csdn.net/youngqj/article/details/7225400