大資料 SQL實現表之間的交集 並集 差集 非交集

2021-09-22 01:50:42 字數 2383 閱讀 7762

登入資料庫

首先,登入mysql的預設資料庫test,我們的驗證從這裡開始。主要涉及3條命令,如下:

mysql -uroot -p # 在linux環境下登入mysql資料庫

show databases; – 顯示mysql下有所有資料庫

use test; – 進入test資料庫

show tables; – 顯示test資料庫下的所有表

建表為了測試方便,我們把模型簡化了,我們就建乙個只有3個字段的人員表,id、name、age,其中id為主鍵。然後插入相應的數值,建表語句如下:

mysql> create table tb_a(id int,name varchar(255),age int,primary key (id));

mysql> create table tb_b(id int,name varchar(255),age int,primary key (id));

mysql> insert into tb_a values (1,『ada』,10);

mysql> insert into tb_a values (2,『bon』,12);

mysql> insert into tb_a values (3,『cat』,15);

mysql> insert into tb_b values (2,『bon』,12);

mysql> insert into tb_b values (4,『dog』,18);

mysql> insert into tb_b values (5,『egg』,20);

最終的表如下:

實現3.1 交集

join是標準sql語句解決交集問題的關鍵字,衍生出inner join、left join、right join、full join等。在這裡我們只是用到簡單的join…on…語句,交集命令如下:select a.id,a.name,a.age from tb_a as a join tb_b as b on a.id =b.id;

當然除了上面做何種思路,也可以通過in關鍵字達到同樣目的,**如下:select * from tb_a where id in (select id from tb_b);

3.2 並集

union就是標準的sql語句解決表合併問題,union是去重的,union all是不去重的,具體**是:select * from tb_a union select * from tb_b;

3.3 差集

由於mysql不支援except欄位,所以我們採用not in,思路是先取a中所有記錄再過濾掉b中有的記錄,具體語句是:select * from tb_a where id not in (select id from tb_b);

3.4 非交集

回到本文的出發點,sql語句中並沒有乙個關鍵字是解決非交集問題的,但是通過上面三個功能的實現,我們可以把非交集轉換為a-b的差集並上b-a的差集的並集,具體語句是:select * from tb_a where id not in (select id from tb_b) union select * from tb_b where id not in (select id from tb_a);

最後總結一下join相關的內容如下:

參考文獻

1.sql求兩表的並集、交集、非交集、差集、結果集排序

2.sql 教程

3.sql 連線(join)

順序表 差並交集的實現

首先建乙個線性表 include using namespace std define list int size 100 初始分配量 define list increment 10 分配增量 typedef int elemtype 元素資料型別 typedef struct sqlist 初始...

資料庫 連線查詢,資料表之間的並交集關係

我們先建立兩個表 person與car person表中的cardid對應的為card表的id,但是由於兩個表未加副鍵約束。所以當person表中插入的cardid在card表中不存在時,不會產生錯誤。sql分為 實際上是求交集。外連線 完全外連線 full join或者full outer joi...

sql求兩表的並集 交集 非交集 差集 結果集排序

create table a id intidentity 1,1 not null primary key,name varchar 20 not null default insert into a name values a insert into a name values b insert...