MySQL實現差集(Minus)和交集(Intersect)

來源:互聯網
上載者:User

MySQL實現差集(Minus)和交集(Intersect)

MySQL沒有實現Minus和Intersect功能,就像它也沒有實現cube的功能一樣。
 
可以用SQL實現同樣的功能,就是麻煩了點。
 
drop table t1;
 
drop table t2;

create table t1(id int primary key,nickname varchar(20),playNum varchar(20));

create table t2(id int primary key,nickname varchar(20),playNum varchar(20));

insert into t1 values(1,1,10);

insert into t1 values(2,2,20);

insert into t1 values(3,3,30);

insert into t2 values(1,1,10);

insert into t2 values(2,2,200);

insert into t2 values(3,33,300);

commit;

MySQL實現交集
 
SELECT id, nickname, playNum, COUNT(*)
 
FROM (SELECT id, nickname, playNum

    FROM t1

    UNION ALL

    SELECT id, nickname, playNum

    FROM t2

    ) a

GROUP BY id, nickname, playNum

HAVING COUNT(*) > 1

MySQL實現差集
 
SELECT t1.id, t1.nickname, t1.playNum
 
FROM t1 LEFT JOIN t2 ON t1.id = t2.id

WHERE t1.nickname != t2.nickname

    OR t1.playNum != t2.playNum;

--------------------------------------分割線 --------------------------------------

Ubuntu 14.04下安裝MySQL

《MySQL權威指南(原書第2版)》清晰中文掃描版 PDF

Ubuntu 14.04 LTS 安裝 LNMP Nginx\PHP5 (PHP-FPM)\MySQL

Ubuntu 14.04下搭建MySQL主從伺服器

Ubuntu 12.04 LTS 構建高可用分布式 MySQL 叢集

Ubuntu 12.04下原始碼安裝MySQL5.6以及Python-MySQLdb

--------------------------------------分割線 --------------------------------------

本文永久更新連結地址:

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.