美文网首页
MySQL UNION 联合查询

MySQL UNION 联合查询

作者: soeben | 来源:发表于2018-10-19 15:46 被阅读0次

    语法

    SELECT * FROM table
    UNION [ALL | DISTINCT]
    SELECT * FROM table
    

    ALL全部数据 DISTINCT去重数据

    例子

    //结构
    CREATE TABLE `user_student`  (
      `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
      `name` varchar(10) NOT NULL,
      `sex` tinyint(4) NOT NULL,
      `tel` char(11) NOT NULL,
      PRIMARY KEY (`id`)
    )ENGINE=InnoDB DEFAULT CHARACTER SET utf8;
    
    CREATE TABLE `user_teacher`  (
      `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
      `name` varchar(10) NOT NULL,
      `sex` tinyint(4) NOT NULL,
      `tel` char(11) NOT NULL,
      PRIMARY KEY (`id`)
    )ENGINE=InnoDB DEFAULT CHARACTER SET utf8;
    
    //查询全部数据
    SELECT * FROM `user_student`
    UNION All
    SELECT * FROM `user_teacher`
    
    //查询去重数据 DISTINCT可选
    SELECT * FROM `user_student`
    UNION DISTINCT
    SELECT * FROM `user_teacher`
    

    相关文章

      网友评论

          本文标题:MySQL UNION 联合查询

          本文链接:https://www.haomeiwen.com/subject/vbayzftx.html