CREATE TABLE emp(ename VARCHAR(10), hiredate DATE, sal DECIMAL(10, 2), deptno INT(2));
CREATE TABLE dept(deptno INT(2), deptname VARCHAR(10));
INSERT INTO emp(ename, hiredate, sal, deptno) VALUES('zzx1', '2000-01-01', '2000', 1);
values后面的顺序应该和字段的排列顺序一致
INSERT INTO emp VALUES('zzx1', '2000-01-01', '2000', 1);
/*ename hiredate sal deptno
------ ---------- ------ --------
zzx1 2000-01-01 200.00 1*/
UPDATE emp SET sal=400 WHERE ename='zzx1';
UPDATE emp a, dept b
SET a.sal=a.sal*b.deptno, b.deptname=a.ename
WHERE a.deptno = b.deptno;
DELETE FROM emp WHERE ename='zzx1';
#普通查询
select * from emp;
#带条件查询
SELECT * FROM emp WHERE ename='zzx1';
SELECT ename, sal FROM emp WHERE ename='zzx1';
#查询deptno字段并去除重复
SELECT DISTINCT deptno FROM emp;
#查询并将以sal排序
SELECT * FROM emp ORDER BY sal;
#对于deptno相同按sal排序
SELECT * FROM emp ORDER BY deptno, sal DESC;
#从查询结果中取第1条返回
SELECT * FROM emp LIMIT 1;
#从查询结果跳过第1条,取2条
SELECT * FROM emp ORDER BY sal LIMIT 1,2;
SELECT COUNT(*) FROM emp;
SELECT deptno, COUNT(1) FROM emp GROUP BY deptno;
SELECT deptno, COUNT(1) FROM emp GROUP BY deptno WITH ROLLUP;
select deptno, count(1) from emp group by deptno having count(1) > 1;
SELECT SUM(sal), MAX(sal), MIN(sal) FROM emp;
SELECT ename, deptname FROM emp, dept WHERE emp.deptno=dept.deptno;
左连接
SELECT ename, deptname FROM emp LEFT JOIN dept ON emp.deptno=dept.deptno;
右连接
SELECT ename, deptname FROM dept RIGHT JOIN emp ON dept.deptno=emp.deptno;
当进入查询的时候,需要的条件是另外一个SELECT语句的结果时候(关键字:in、not in、=、!=、exists、not exists等)
SELECT * FROM emp WHERE deptno IN(SELECT deptno FROM dept);
#如果查询记录为一可以使用=代替in
SELECT * FROM emp WHERE deptno = (SELECT deptno FROM dept);
将两个表的数据按照一定的查询条件查询出来后,将结果全并到一起显示出来
UNION ALL
SELECT deptno FROM emp
UNION ALL
SELECT deptno FROM dept;
UNION
SELECT deptno FROM emp
UNION
SELECT deptno FROM dept;