首页 > 代码库 > MySQL笔记
MySQL笔记
MySQL语句执行步骤:
总是先执行FROM语句,最后执行LIMIT语句,其中每个操作都产生一个临时表,下一条语句正在此临时表基础上再进行操作,只有最后的临时表才是真正的返回结果
FROM--->将左边的表和右边的表进行笛卡尔积
ON--->
JOIN--->
WHERE--->
GROUP BY--->
CUBE | ROLLUP-->
HAVING--->
SELECT--->
DISTINCT--->
ORDER BY--->
LIMIT--->
sql优化
尽量避免在列上运算
用整型设计索引
join时使用小结果集驱动大结果集
列出查询列,尽量少用*号代替
插入时,使用批量插入
索引失效:
在复合索引中顺序不同使索引失效
使用or时不是每个列都建立索引
使用like关键字时‘%部‘,匹配关键字放在%号后面时失效
字符串没加‘‘
分页;
/*
*基本分页
*LIMIT 20,3 从第20行开始的后3行 21,22,23
*
*/
#SELECT * from books LIMIT 20,3;
/*
*子查询的分页方式
*
*
SELECT * from books WHERE id >=
(SELECT id from books WHERE count=20 ORDER BY id LIMIT 10,1) LIMIT 2;
*/
/*
*SQL_CALC_FOUND_ROWS 告诉Mysql将sql所处理的行数记录下来,FOUND_ROWS() 则取到了这个纪录。 虽然也是两个语句,但是只执行了一次主查询,所以效率比原来要高很多
*/
/*select SQL_CALC_FOUND_ROWS * FROM books WHERE id > 10 LIMIT 10;
SELECT FOUND_ROWS();*/
分组:
SELECT name,count(*) AS num FROM employee_tbl GROUP BY name HAVING num > 1;
存储过程:
在实际项目中想只保存最近几天的数据,这时候就写自定义计划,也就是存储函数,这是预先写好的sql语句集合,预定好时间去执行该存储过程
创建
delimiter //
create procedure example_if(in x int)
begin
if x=1 then
select 1;
elseif x=2 then
select 2;
else
select 3;
end if;
end
调用
CALL ccc(1)
SELECT * from users ;
SELECT id+5 from users;
SELECT * FROM users where name = ‘aa‘ GROUP BY id DESC;
SELECT * FROM users WHERE id IN(1,3);
SELECT * from users WHERE id BETWEEN 2 AND 5;
SELECT COUNT(age) FROM users;
SELECT COUNT(*) FROM users;
-- 随机取出2条数据
SELECT * FROM users ORDER BY RAND() LIMIT 2;
-- 字符串拼接
SELECT CONCAT(name,age) FROM users;
-- DISTINCT显示name,id,score组合起来是否相同
SELECT DISTINCT name,id,score FROM users;
-- MAX
SELECT * FROM users WHERE id=(SELECT MAX(id) from users);
SELECT name,age,MAX(score) MAXScore from users ORDER BY name ;
-- SUM
SELECT score FROM users WHERE id IN(2,5,4);
SELECT SUM(score) FROM users WHERE id IN(2,5,4);
SELECT * from users GROUP BY name;
-- 部门薪水最高的
SELECT dept, MAX(salary) AS maximum
FROM staff
GROUP BY dept;
-- 每个部门薪水总和
SELECT dept, SUM(salary) AS 薪水总和
FROM staff
GROUP BY dept HAVING ;
-- HAVING是在GROUP BY的产生的临时表中在执行操作
SELECT *
FROM staff
GROUP BY dept HAVING edlevel=5;
-- 查询公司2010年入职的各个部门每个级别里的最高薪水
SELECT DEPT, edlevel, MAX( SALARY ) AS MAXIMUM
FROM staff
WHERE hiredate > ‘2010-01-01‘
GROUP BY dept,edlevel;
-- 寻找雇员数超过2个的部门的最高和最低薪水
SELECT DEPT, MAX( SALARY ) AS MAXIMUM, MIN( SALARY ) AS MINIMUM
FROM staff
GROUP BY DEPT
HAVING COUNT( * ) >2
ORDER BY DEPT
-- 寻找雇员平均工资大于3000的部门的最高和最低薪水:
SELECT DEPT, MAX( SALARY ) AS MAXIMUM, MIN( SALARY ) AS MINIMUM
FROM staff
GROUP BY DEPT
HAVING AVG( SALARY ) >3000
ORDER BY DEPT
-- 返回钱5行
select * from staff limit 5;
-- 同上
SELECT * from staff limit 0,5;
-- 2后面的5行
select * from staff limit 2,5;
-- limit优化 将id先排序,取出第3行的第一个,再根据where语句取出此id后面的数据,即指定数据
SELECT * from staff WHERE id>=
(SELECT id from staff ORDER BY id LIMIT 3,1) LIMIT 4;
-- 将两列合并成一列
SELECT name as p from staff
UNION
SELECT dept as p FROM staff;
-- 取出表中的一般数据
select top 50 persent from staff;
SELECT TOP 2 *
FROM staff
WHERE ( id NOT IN
(SELECT TOP 5 id from staff ORDER BY id))
ORDER BY id;
MySQL笔记