(准备)

CREATE DATABASE db2;

CREATE TABLE dept(
	id INT PRIMARY KEY AUTO_INCREMENT,
	NAME VARCHAR(20)
);

INSERT INTO dept (NAME) VALUES('开发部'),('市场部'),('财务部');

CREATE TABLE emp(
	id INT PRIMARY KEY AUTO_INCREMENT,
	NAME VARCHAR(10),
	gender CHAR(1),
	salary DOUBLE,
	join_date DATE,
	dept_id INT,
	FOREIGN KEY (dept_id) REFERENCES dept(id)
);

INSERT INTO emp(NAME,gender,salary,join_date,dept_id)  VALUES('qqq','男',7500.0,'2019-02-01',1);
INSERT INTO emp(NAME,gender,salary,join_date,dept_id)  VALUES('谢自','女',7200.0,'2011-02-01',2);
INSERT INTO emp(NAME,gender,salary,join_date,dept_id)  VALUES('马天','女',10000.0,'2011-02-01',3);
INSERT INTO emp(NAME,gender,

1.内连接查询

  笛卡尔乘积:取两个集合的所有组合情况。

    SELECT * FROM emp,dept;

  完成多表查询需要消除无用数据。

    SELECT * FROM emp,dept WHERE emp.`dept_id` = dept.`id`;

        

 

 

     SELECT emp.`name`,emp.`gender`,dept.`name` AS name2 FROM emp,dept WHERE emp.`dept_id` = dept.`id`;  

        

 

 

 2.显式内连接:

  SELECT * FROM emp JOIN dept ON emp.`dept_id` = dept.`id`;

  

 

 

 3。外连接

  左外连接:查询左表的所有记录以及交集部分

    

SELECT
    t1.*,t2.`name`
FROM
    emp t1 LEFT JOIN dept t2
ON
    t1.`dept_id` = t2.`id`;

 

 

  右外连接:查询有表的所有记录以及交集部分

SELECT
	t1.*,t2.`name`
FROM
	emp t1 RIGHT JOIN dept t2
ON
	t1.`dept_id` = t2.`id`;

  

 

 3.子查询

  查询中的嵌套查询

  #查询工资最高的员工

    SELECT MAX(emp.`salary`) FROM emp;

  #查询工资等于表中最大的

    SELECT * FROM emp WHERE emp.`salary` = (SELECT MAX(salary) FROM emp);

    

 

   #查询多行

    #查询财务部和市场部的所有信息

    SELECT * FROM emp WHERE dept_id IN (SELECT id FROM dept WHERE NAME = '财务部' OR NAME = '市场部');

  

Posted on 2022-06-07 11:08  LutixiaGit  阅读(44)  评论(0编辑  收藏  举报