zoukankan      html  css  js  c++  java
  • mysql 并集、交集、差集

    创建两个表

     
    CREATE TABLE `object_a` (
     
    `id` bigint(20) NOT NULL AUTO_INCREMENT,
     
    `oname` varchar(50) DEFAULT NULL,
     
    `odesc` varchar(50) DEFAULT NULL,
     
    `create_time` datetime DEFAULT NULL,
     
    PRIMARY KEY (`id`)
     
    ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1

    添加数据

    CREATE TABLE `object_b` (
     
    `id` bigint(20) NOT NULL AUTO_INCREMENT,
     
    `oname` varchar(50) DEFAULT NULL,
     
    `odesc` varchar(50) DEFAULT NULL,
     
    `create_time` datetime DEFAULT NULL,
     
    PRIMARY KEY (`id`)
     
    ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1

    添加数据

    查询并集(union all)

    SELECT oname,odesc FROM object_a
     
    UNION ALL
     
    SELECT oname,odesc FROM object_b

    结果如下

    查询并集(union)

    SELECT oname,odesc FROM object_a
     
    UNION
     
    SELECT oname,odesc FROM object_b

    结果如下


    PS:union自带去重

    查询交集

    SELECT a.oname,a.odesc FROM object_a a INNER JOIN object_b b ON a.oname=b.oname AND a.odesc=b.odesc

    等价于

    SELECT a.oname,a.odesc FROM object_a a INNER JOIN object_b b USING(oname,odesc)

    结果如下

     


    PS:别的数据库可以试试这种写法

    SELECT oname,odesc FROM object_a
     
    INTERSECT
     
    SELECT oname,odesc FROM object_b

    查询差集

    SELECT a.oname, a.odesc
     
    FROM
     
    object_a a
     
    LEFT JOIN object_b b
     
    ON a.oname = b.oname
     
    AND a.odesc = b.odesc
     
    WHERE b.id IS NULL

    结果如下

    PS:别的数据库可以试试这种写法

    SELECT a.oname, a.odesc FROM object_a a
     
    MINUS
     
    SELECT b.oname, b.odesc FROM object_b b
  • 相关阅读:
    一个C# usb与mcu通信的程序,附代码
    基于C#音乐播放器(附代码)
    基于C#俄罗斯方块
    FTP方式部署Azure Web App
    微信接口小例
    基于来信码的短信通知平台
    基于Windows服务的WCF
    基于IIS的WCF
    基于.NET的Excel开发:单元格区域的操作(读取、赋值、边框和格式)
    .NET通过RFC读取SAP数据
  • 原文地址:https://www.cnblogs.com/-mrl/p/13610265.html
Copyright © 2011-2022 走看看