MySQL数据库专栏(九)内联查询
1、内联查询概述
MySQL中的内联查询(Inner Join)是一种SQL查询操作,用于结合两个或多个表中的行。当两个表通过共同的字段(通常是外键和主键)相关联时,内联查询会返回这些表中所有匹配的行。如果在一个表中存在与另一个表连接条件不匹配的行,那么这些行就不会出现在查询结果中。
2、应用说明及准备
在实际开发中,我们会联合多个表来实现查询,比如把员工表和部门表联合起来就同时可以看到员工和所在部门的信息,员工表有员工姓名,手机号,岗位,所属部门等信息,部门表有部门名称、部门编号等信息,表结构如下:
DROP TABLE IF EXISTS `t_department`;
CREATE TABLE IF NOT EXISTS `t_department` (
`department_no` INT unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
`department_name` varchar(128) NOT NULL DEFAULT '' COMMENT '部门名称',
PRIMARY KEY (`department_no`),
UNIQUE KEY `department_name` (`department_name`)
) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_bin;
DROP TABLE IF EXISTS `t_employee`;
CREATE TABLE IF NOT EXISTS `t_employee` (
`id` INT unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
`department_no` INT unsigned NOT NULL DEFAULT '0' COMMENT '部门表id',
`name` varchar(128) NOT NULL DEFAULT '' COMMENT '登录名',
`position` varchar(128) NOT NULL DEFAULT '' COMMENT '岗位',
`phone` char(11) NOT NULL DEFAULT '' COMMENT '手机号',
PRIMARY KEY (`id`),
INDEX `name` (`name`),
UNIQUE KEY `phone` (`phone`)
) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_bin;
ALTER TABLE t_department AUTO_INCREMENT = 10000;
insert into t_department(`department_name`) values('软件部');
insert into t_department(`department_name`) values('测试部');
insert into t_employee(`department_no`,`name`,`position`,`phone`) values('10000','张三','开发','13533265485');
insert into t_employee(`department_no`,`name`,`position`,`phone`) values('10000','李四','开发','13533265486');
insert into t_employee(`department_no`,`name`,`position`,`phone`) values('10001','张五','测试','13533265487');
insert into t_employee(`department_no`,`name`,`position`,`phone`) values('10001','李六','测试','13533265488');
3、内联查询语法结构
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
4、使用实例
Select e.name,e.position,d.department_name,e.phone from t_employee e inner join t_department d on e.department_no=d.department_no;
+--------+----------+-----------------+-------------+
| name | position | department_name | phone |
+--------+----------+-----------------+-------------+
| 张三 | 开发 | 软件部 | 13533265485 |
| 李四 | 开发 | 软件部 | 13533265486 |
| 张五 | 测试 | 测试部 | 13533265487 |
| 李六 | 测试 | 测试部 | 13533265488 |
+--------+----------+-----------------+-------------+