8.21 SQL的学习:如何连接两张表

在原先的基础上,我们又学习了一些比较复杂的SQL语句。
1.首先我们来创建两张表,我们要将两张表的共同部分联系在一起。

CREATE TABLE employee_china(
  id INT,
  NAME VARCHAR(50)
);
CREATE TABLE employee_usa(
  id INT,
  NAME VARCHAR(50)
);

我们先来查询两张表所有信息(这里用到了关键字UNION):

SELECT * FROM employee_china UNION SELECT * FROM employee_usa;
SELECT * FROM employee_china UNION ALL SELECT * FROM employee_usa;

2.我们再来创建两张表(员工表和部门表)

CREATE TABLE department(
   id INT,
   NAME VARCHAR(50)
);
CREATE TABLE employee(
   id INT,
   NAME VARCHAR(50),
   depno INT
);

连接两张表:

SELECT e.id,e.name AS '员工名',d.name AS '部门' FROM employee e,department d WHERE e.depno=d.id;

效果如图:
8.21 SQL的学习:如何连接两张表_第1张图片
3.外连接(左连接、右连接)

SELECT e.id,e.name AS '员工名',d.name AS '部门' FROM employee e LEFT OUTER JOIN department d WHERE e.depno=d.id;
SELECT e.id,e.name AS '员工名',d.name AS '部门' FROM employee e LEFT OUTER JOIN department d WHERE e.depno=d.id;
SELECT e.id,e.name AS '员工名',d.name AS '部门' FROM employee e RIGHT OUTER JOIN department d WHERE e.depno=d.id WHERE e.id=1;

8.21 SQL的学习:如何连接两张表_第2张图片
4.我们再来创建两张表。

CREATE  TABLE depart(
depno INT PRIMARY KEY,
NAME VARCHAR(50),
location  VARCHAR(50),
setuptime TIMESTAMP
);
CREATE TABLE emp(
 empno INT PRIMARY KEY,
 ename VARCHAR(50),
 job VARCHAR(50),
 mgr INT,
 hiredate DATE,
 sal DECIMAL(7,2),
 comm DECIMAL(7,2),
 depno INT,
 CONSTRAINT fk_emp_depart FOREIGN KEY(depno) REFERENCES depart(depno)
);

查询练习:

SELECT * FROM emp WHERE sal>(SELECT sal FROM emp WHERE ename='林同学')
SELECT * FROM emp WHERE depno=(SELECT depno FROM emp WHERE ename='天骏')
工资高于技术部所有员工的工资
SELECT * FROM emp WHERE sal>(SELECT MAX(sal) FROM emp WHERE depno='20');

你可能感兴趣的:(学习,MySQL)