@(跃迁之路)专栏

叨叨两句

  1. 技术的精进不能只是简单的刷题,而应该是不断的“刻意”练习
  2. 该系列改版后正式纳入【跃迁之路】专栏,持续更新

刻意练习——MySQL

2018.04.02

题目描述

DROP TABLE IF EXISTS test1;
CREATE TABLE test1 (
id int(11) NOT NULL AUTO_INCREMENT,
username varchar(20) NOT NULL,
course varchar(20) NOT NULL,
score bigint(20) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

INSERT INTO test1 VALUES ('1', '张三', '数学', '34');
INSERT INTO test1 VALUES ('2', '张三', '语文', '44');
INSERT INTO test1 VALUES ('3', '张三', '英语', '54');
INSERT INTO test1 VALUES ('4', '李四', '数学', '134');
INSERT INTO test1 VALUES ('5', '李四', '语文', '144');
INSERT INTO test1 VALUES ('6', '李四', '英语', '154');
INSERT INTO test1 VALUES ('7', '王五', '数学', '234');
INSERT INTO test1 VALUES ('8', '王五', '语文', '244');
INSERT INTO test1 VALUES ('9', '王五', '英语', '254');

查出以下结果

法1

SELECT
    A.username,A.score as '数学',B.score as '语文',C.score as '英语'
FROM 
(select username,course,score from test1 where course = '数学') A,
(select username,course,score from test1 where course = '语文') B,
(select username,course,score from test1 where course = '英语') C
WHERE
    A.username = B.username
and B.username = C.username

法2【推荐】

select
    username,sum(case course when '数学' then score else 0 end ) as '数学',
sum(case course when '语文' then score else 0 end ) as '语文',
sum(case course when '英语' then score else 0 end ) as '英语'
FROM
    test1
group by username

2018.04.03

题目描述

在audit表上创建外键约束,其emp_no对应employees_test表的主键id。
CREATE TABLE employees_test(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);

CREATE TABLE audit(
EMP_no INT NOT NULL,
create_date datetime NOT NULL
);

DROP TABLE audit;
CREATE TABLE audit(
    EMP_no INT NOT NULL,
    create_date datetime NOT NULL,
    FOREIGN KEY(EMP_no) REFERENCES employees_test(ID)
);

2018.04.04

由于视图 emp_v 的记录是从 employees 中导出的,所以要判断两者中相等的数据,只需要判断emp_no相等即可。
方法一:用 WHERE 选取二者 emp_no 相等的记录

SELECT em.* FROM employees AS em, emp_v AS ev WHERE em.emp_no = ev.emp_no
方法二:用 INTERSECT 关键字求 employees 和 emp_v 的交集
可参考:http://www.sqlite.org/lang_select.html

SELECT * FROM employees INTERSECT SELECT * FROM emp_v
方法三:仔细一想,emp_v的全部记录均由 employees 导出,因此可以投机取巧,直接输出 emp_v 所有记录

SELECT * FROM emp_v
【错误方法:】用以下方法直接输出 *,会得到两张表中符合条件的重复记录,因此不合题意,必须在 * 前加表名作限定

SELECT * FROM employees, emp_v WHERE employees.emp_no = emp_v.emp_no

2018.04.05

题目描述
将所有获取奖金的员工当前的薪水增加10%。
create table emp_bonus(
emp_no int not null,
recevied datetime not null,
btype smallint not null);
CREATE TABLE salaries (
emp_no int(11) NOT NULL,
salary int(11) NOT NULL,
from_date date NOT NULL,
to_date date NOT NULL, PRIMARY KEY (emp_no,from_date));

UPDATE salaries SET salary = salary * 1.1 WHERE emp_no IN
(SELECT s.emp_no FROM salaries AS s INNER JOIN emp_bonus AS eb 
ON s.emp_no = eb.emp_no AND s.to_date = '9999-01-01')

Wall_Breaker
2.1k 声望1.2k 粉丝

生死之间,就是我的跃迁之路,全程记录,欢迎见证