MySQL UNION 联合查询

2018-10-19  本文已影响0人  soeben

语法

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`
上一篇下一篇

猜你喜欢

热点阅读