• 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语言文件
    java课程设计-彩票购买抽奖程序
    面向对象设计大作业——图书馆
    有理数类设计
    图总结
    编译器、编辑器、文件、IDE等常见概念辨析
    树、二叉树、查找算法总结
    互评:数据结构、算法及线性表总结
    c语言文件
    第二次博客园作业
  • 原文地址:https://www.cnblogs.com/-mrl/p/13610265.html
Copyright © 2020-2023  润新知