#第十章 数据处理之增删改
SELECT * FROM emp1;
#插入数据
INSERT INTO emp1(id,NAME,salary,hire_date)
SELECT employee_id,last_name,salary,hire_date #查询的字段一定要与添加到表的字段一一对应
FROM employees
WHERE department_id IN(60,70);
DESC emp1;
DESC employees;
#更新数据
UPDATE emp1
SET hire_date=CURDATE()
WHERE id=5;
#同时修改一条数据的多个字段
UPDATE emp1
SET hire_date=CURDATE(),salary=6000
WHERE id=4;
#将表中姓名包含字符a的提薪20%,以下报错,修改数据时存在不成功的情况,可能是由于约束原因
UPDATE emp1
SET salary=salary*1.2
WHERE emp1.name
LIKE=‘%a%’;
#删除数据 delete from tablename where
DELETE FROM emp1
WHERE id=1;
DELETE FROM departments
WHERE department_id=50;
SELECT deptid,SUM(CASE sex WHEN ‘男’ THEN 1 ELSE 0 END) male_count,SUM(CASE sex WHEN ‘女’ THEN 1 ELSE 0 END) female_count
FROM emp_sex
GROUP BY deptid;
SELECT DISTINCT NAME,COUNT(NAME)FROM business
WHERE orderdate LIKE’2017-04%';
#第十三章 约束
SELECT * FROM information_schema.TABLE_CONSTRAINTS
WHERE table_name=‘employees’;
CREATE DATABASE test13;
USE test13;
CREATE TABLE test1(
id INT NOT NULL,
last_name VARCHAR(15)NOT NULL,
email VARCHAR(25),
salary DECIMAL(10,2)
);
DESC test1;
INSERT INTO test1(id,last_name,email,salary)
VALUES(1,‘tom’,‘tom@126.com’,3600);
INSERT INTO test1(id,last_name,email,salary)
VALUES(2,‘jerry’,‘teee@126.com’,3600);
INSERT INTO test1(id,last_name) #给指定字段赋值,满足其非空的约束
VALUES(3,‘lili’);
SELECT *FROM test1;
UPDATE test1
SET email=‘tom122.com’
WHERE id=2;
#在alter table时添加约束
DESC test1;
ALTER TABLE test1
MODIFY email VARCHAR(25)NOT NULL;
SELECT * FROM test1;
CREATE TABLE test2(
id INT NOT NULL UNIQUE
);
SHOW INDEX FROM test1;
SHOW INDEX FROM test2;
#学生表
CREATE TABLE student(
sid INT, #学号
sname VARCHAR(20), #姓名
tel CHAR(11) UNIQUE KEY, #电话
cardid CHAR(18) UNIQUE KEY #身份证号
);
#课程表
CREATE TABLE course(
cid INT, #课程编号
cname VARCHAR(20) #课程名称
);
#选课表
CREATE TABLE student_course(
id INT,
sid INT,
cid INT,
score INT,
UNIQUE KEY(sid,cid) #复合唯一
);
INSERT INTO student VALUES(1,‘张三’,‘13710011002’,‘101223199012015623’);#成功
INSERT INTO student VALUES(2,‘李四’,‘13710011003’,‘101223199012015624’);#成功
INSERT INTO course VALUES(1001,‘Java’),(1002,‘MySQL’);#成功
SELECT * FROM student;
INSERT INTO student_course VALUES
(1, 1, 1001, 89),
(2, 1, 1002, 90),
(3, 2, 1001, 88),
(4, 2, 1002, 56);#成功
SELECT * FROM student_course;
INSERT INTO student_course VALUES (5, 1, 1001, 88);#失败,违反sid-cid的复合唯一
SELECT * FROM information_schema.TABLE_CONSTRAINTS
WHERE table_name=‘student_course’;