明輝手游網(wǎng)中心:是一個免費提供流行視頻軟件教程、在線學習分享的學習平臺!

mysql 查詢結(jié)果取交集的方法

[摘要]本文將詳細介紹MySQL中如何實現(xiàn)以SQL查詢返回的結(jié)果集取交集的實現(xiàn)方法,需要的朋友可以參考1 MySQL中如何實現(xiàn)以下SQL查詢 (SELECT S.Name FROM STUDENT S, TRANSCRIPT T WHERE S.StudId = T.StudId AND T.CrsCod...
本文將詳細介紹MySQL中如何實現(xiàn)以SQL查詢返回的結(jié)果集取交集的實現(xiàn)方法,需要的朋友可以參考

1
MySQL中如何實現(xiàn)以下SQL查詢
(SELECT S.Name
FROM STUDENT S, TRANSCRIPT T
WHERE S.StudId = T.StudId AND T.CrsCode = 'CS305')
INTERSECT
(SELECT S.Name
FROM STUDENT S, TRANSCRIPT T
WHERE S.StudId = T.StudId AND T.CrsCode = 'CS315')
請各位不吝賜教,小弟先謝過~
解:
取交集
select a.* from
(
SELECT S.Name
FROM STUDENT S, TRANSCRIPT T
WHERE S.StudId = T.StudId AND T.CrsCode = 'CS305'
) as a
cross join
(
SELECT S.Name
FROM STUDENT S, TRANSCRIPT T
WHERE S.StudId = T.StudId AND T.CrsCode = 'CS315'
) as b on a.Name = b.Name;

2.
SELECT * FROM (
SELECT DISTINCT col1 FROM t1 WHERE...
UNION ALL
SELECT DISTINCT col1 FROM t1 WHERE...
) AS tbl
GROUP BY tbl.col1 HAVING COUNT(*) = 2

3.
交集:
SELECT * FROM table1 AS a JOIN table2 AS b ON a.name =b.name
舉例:
表a:
FieldA
001
002
003
表b:
FieldA
001
002
003
004
請教如何才能得出以下結(jié)果集,即表A, B行交集
FieldA
001
002
003
答案:select a.FieldA from a inner join b on a.FieldA=b.FieldA
差集:
NOT IN 表示差集
SELECT * FROM table1 WHERE name NOT IN (SELECT name FROM table2)

以上就是mysql 查詢結(jié)果取交集的方法的詳細內(nèi)容,更多請關(guān)注php中文網(wǎng)其它相關(guān)文章!


學習教程快速掌握從入門到精通的SQL知識。