Re: [SQL ] mysql如何交集查詢條件?

看板Database作者 (TeemingVoid)時間10年前 (2014/01/21 00:53), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/4 (看更多)
※ 引述《SonEat (善液)》之銘言: : table : ID element : 1 Bi : 1 Na : 2 Bi : 2 Na : 2 O : 3 Bi : 3 C : 因為mysql沒有Intersection查詢的功能可用 : 因此我的問題 : 1. 我想查出至少包含Bi與Na的ID 也就是查詢結果為 1,2 : 我原本用select * from table where element='Bi' and element='Na'結果會查出空集合 : select * from table where element='Bi' or element='Na' 則會查出 1,2,3 -- 依你提出的資料為例: use test; create table MoleculeElement ( MoleculeID int, Element varchar(2) ); insert into MoleculeElement values (1,'Bi'),(1,'Na'), (2,'Bi'),(2,'Na'),(2,'O'), (3,'Bi'),(3,'C'); -- 利用子查詢分別找出兩個元素的資料,再以 inner join 取交集 -- 查出至少包含 Bi 與 Na 的 ID,也就是查詢結果為 1, 2 select A.MoleculeID from ( select MoleculeID, Element from MoleculeElement where Element = 'Bi' ) as A join ( select MoleculeID, Element from MoleculeElement where Element = 'Na' ) as B on (A.MoleculeID = B.MoleculeID); : 2. 我想查出只有包含Bi與Na兩種元素的ID 也就是查詢結果為 1 -- 繼續找出元素數量正好是二的分子,再取一次交集 select MoleculeID from ( select MoleculeID, Element from MoleculeElement where Element = 'Bi' ) as A join ( select MoleculeID, Element from MoleculeElement where Element = 'Na' ) as B using (MoleculeID) join ( select MoleculeID from MoleculeElement group by MoleculeID having count(*) = 2 ) as C using (MoleculeID) -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.38.74.223

01/21 10:32, , 1F
兩個都成功了,非常感謝大大
01/21 10:32, 1F
文章代碼(AID): #1ItLHiMe (Database)
討論串 (同標題文章)
文章代碼(AID): #1ItLHiMe (Database)