Mysql联合查询union和union all的使用介绍

本文介绍如何在SQL中进行联合查询,并演示了不同类型的UNION查询,包括UNION ALL(保留重复项)、标准UNION(去除重复项)以及带来源标记的联合查询。此外还展示了如何创建和填充数据库表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://www.itxm.net/a/shujuku/2016/1205/841.html

https://www.cnblogs.com/wangyayun/p/6133540.html

适应于少量表的级联查询

-- 建表、填充数据
SET FOREIGN_KEY_CHECKS=0;

DROP TABLE IF EXISTS `company`;
CREATE TABLE `company` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

INSERT INTO `company` VALUES ('1', '小米');
INSERT INTO `company` VALUES ('2', '华为');

DROP TABLE IF EXISTS `fixshop`;
CREATE TABLE `fixshop` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '维修点',
  `title` varchar(50) NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

INSERT INTO `fixshop` VALUES ('3', '魅族', '0');
INSERT INTO `fixshop` VALUES ('4', '苹果', '0');

DROP TABLE IF EXISTS `shop`;
CREATE TABLE `shop` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `shopname` varchar(50) NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

INSERT INTO `shop` VALUES ('1', '小米', '0');
INSERT INTO `shop` VALUES ('4', '苹果', '1');

-- union 及 union on 的使用

-- union all 查询所有结果(包含重复项)
(SELECT id,name from company ) union all (SELECT id,title from fixshop ) union all (SELECT id,shopname from shop );

-- union  查询结果(不包含重复项)
(SELECT id,name from company ) union  (SELECT id,title from fixshop ) union  (SELECT id,shopname from shop );

-- 查询结果并标记来源
(SELECT id,name,1 as class from company ) union  (SELECT id,title,2 as class from fixshop ) union  (SELECT id,shopname,3 as class from shop where status = 0);

-- 模糊查询结果(类似应用首页的全模块搜索)
(SELECT id,name,1 as class from company where name LIKE "%米%" ) union  (SELECT id,title,2 as class from fixshop where title LIKE "%米%") union  (SELECT id,shopname,3 as class from shop where status = 0 and shopname LIKE "%米%") ORDER BY class;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值