MySQL-练习1
CREATE TABLE department(
id INT PRIMARY KEY AUTO_INCREMENT,
dname VARCHAR(30) NOT NULL UNIQUE,
address VARCHAR(40),
leeder VARCHAR(20) NOT NULL
);
INSERT INTO department VALUE
(NULL, "财务部", "北京市", "李老板"),
(NULL, "销售部", "上海市", "王老板"),
(NULL, "开发部", "广州市", "胡老板"),
(NULL, "客服部", "深圳市", "曾老板");
CREATE TABLE employees(
id INT PRIMARY KEY AUTO_INCREMENT,
ename VARCHAR(20) NOT NULL,
sex VARCHAR(10),
phone INT UNIQUE,
hiredate DATE,
salary INT,
depa_id INT,
CONSTRAINT emp_dep_fk FOREIGN KEY (depa_id) REFERENCES department(id)
);
INSERT INTO employees VALUE
(NULL, "小虎", "男", 10086, "2016-04-27", 6000, 1),
(NULL, "小林", "男", 10000, "2017-08-11", 9000, 2),
(NULL, "小花", "女", 10010, "2015-11-02", 3000, 2),
(NULL, "小李", "男", 10001, "2011-08-19", 2000, 2),
(NULL, "小丽", "女", 10085, "2018-12-01", 6000, NULL),
(NULL, "小红", "女", 10011, "2017-09-07", NULL, 3),
(NULL, "小胡", "男", 12315, "2008-06-15", 8000, 4),
(NULL, "小廖", "男", 12306, "2021-10-30", 7000, 4);
SELECT t1.*, t2.`dname`, t2.`leeder`
FROM employees t1, department t2 WHERE t1.`depa_id` = t2.`id`;
SELECT t1.*, t2.`dname`, t2.`leeder`
FROM employees t1 INNER JOIN department t2 ON t1.`depa_id` = t2.`id`;
SELECT t1.*, t2.`dname`
FROM employees t1 LEFT OUTER JOIN department t2 ON t1.`depa_id` = t2.id;
SELECT t1.*,t2.`dname`
FROM department t2 RIGHT OUTER JOIN employees t1 ON t1.`depa_id` = t2.id;
SELECT * FROM employees WHERE salary = (SELECT MAX(salary) FROM employees);
SELECT * FROM employees WHERE salary < (SELECT AVG(salary) FROM employees);
SELECT * FROM employees WHERE depa_id IN(SELECT id FROM department WHERE dname IN ("财务部", "开发部"));
SELECT * FROM (SELECT * FROM employees WHERE employees.`hiredate` > "2016-00-00") t1, department t2
WHERE t1.`depa_id` = t2.`id`;
SELECT * FROM employees t1, department t2 WHERE t1.`depa_id` = t2.`id` AND t1.`hiredate` > "2016-00-00";
|