程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> MYSQL數據庫 >> 關於MYSQL數據庫 >> MySQL 查詢結果取交集的實現方法

MySQL 查詢結果取交集的實現方法

編輯:關於MYSQL數據庫
1
MySQL中如何實現以下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
請教如何才能得出以下結果集,即表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)
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved