在論壇看到的乙個問題這裡總結下:
create tableconsume
(
id
varchar(11) not null,
tid
varchar(11) not null
) collate=』utf8_general_ci』
engine=myisam
; insert intoconsume
(id
,tid
) values (『1』, 『11』);
insert intoconsume
(id
,tid
) values (『2』, 『14』);
insert intoconsume
(id
,tid
) values (『3』, 『12』);
create tableteacher
(
id
varchar(11) not null,
tname
varchar(11) not null,
tdate
datetime not null
) collate=』utf8_general_ci』
engine=myisam
; insert intoteacher
(id
,tname
,tdate
) values (『10』, 『***』, 『2008-01-22 21:54:27』);
insert intoteacher
(id
,tname
,tdate
) values (『11』, 『支老師』, 『2008-01-21 21:54:27』);
insert intoteacher
(id
,tname
,tdate
) values (『13』, 『宋老師』, 『2008-01-28 21:54:27』);
insert intoteacher
(id
,tname
,tdate
) values (『14』, 『魏老師』, 『2008-01-29 21:54:27』);
insert intoteacher
(id
,tname
,tdate
) values (『15』, 『金老師 『, 『2008-01-30 21:54:27』);
insert intoteacher
(id
,tname
,tdate
) values (『16』, 『趙老師』, 『2008-01-19 21:54:27』);
insert intoteacher
(id
,tname
,tdate
) values (『17』, 『張老師』, 『2008-01-18 21:54:27』);
insert intoteacher
(id
,tname
,tdate
) values (『18』, 『嚴老師』, 『2008-01-17 21:54:27』);
insert intoteacher
(id
,tname
,tdate
) values (『12』, 『龔老師』, 『2008-01-25 21:54:27』);
insert intoteacher
(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
然後將兩張錶連起來
這裡說明下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即可得到這個差集類似第二張圖
以上是我的交集與差集的理解。
參考:
mysql查詢交集 並集 差集
查詢同一張表就把table寫成一樣 查詢交集,由於mysql不支援intersect,可以使用以下方案 select from select from table where val 10 as t1 inner join select from table where val 11 as t2 w...
交集並集差集
1 內連線 select from student a inner join sc b on a.sno b.sno 左連線 select from student a left join sc b on a.sno b.sno 差集 select sno from student except s...
golang交集,差集
從今天起寫一些golang 函式實現php庫函式的功能 php 函式 array diff,array intersect package php arraydiff 模擬php array diff函式 func arraydiff array1 inte ce othersparams inte...