标签:过程 逻辑 mda 取出 如何 初始化 cto 读取 myisam
查询性能优化
是否向数据库请求了不需要的数据
MySQL是否在扫描额外的记录
优化count查询
SELECT COUNT(*) FROM City WHERE ID > 5;
SELECT (SELECT COUNT(*) FROM City) - COUNT(*) FROM City WHERE ID <=5;
使用近似值
优化关联查询
优化子查询
优化limit分页(索引章节有提到)
SELECT film_id,description FROM film ORDER BY title limit 10000,5
SELECT film_id, film.description FROM film JOIN ( SELECT film_id FROM film ORDER BY title LIMIT 10000,5 ) AS lim USING (film_id);
SELECT film_id,description FROM film WHERE position BETWEEN 10000 AND 10004 ORDER BY position;-- 确认BETWEEN的边界[]
优化UNION查询
使用用户自定义变量
SET @min_actor := (SELECT MIN(act_id) FROM actor); SELECT .. FROM actor WHERE act_id > @min_actor;
优化排名顺序
SET @rownum := 0; SELECT actor_id,@rownum := @rownum + 1 AS rownum FROM actor LIMIT 3;
SELECT actor_id, COUNT(*) AS cnt FROM film_actor GROUP BY actor_id ORDER BY cnt DESC LIMIT 10;
SET @curr_cnt := 0 ,@prev_cnt := 0 ,@rank := 0; SELECT actor_id, @curr_cnt := COUNT(*) AS cnt, @rank := IF (prev_cnt <> @curr_cnt,@rank + 1 ,@rank) AS rank, @prev_cnt := @curr_cnt AS dummy FROM ( SELECT actor_id, COUNT(*) AS cnt FROM film_actor GROUP BY actor_id ORDER BY cnt DESC LIMIT 10 ) AS der;
避免重复查询刚刚更新的数据
UPDATE t1 SET lastUpdated = NOW() WHERE id = 1; SELECT lastUpdated FROM t1 WHERE id = 1;
UPDATE t1 SET lastUpdated = NOW() WHERE id = 1 AND @now := NOW(); SELECT @now;
编写偷懒的UNION
SELECT id FROM users WHERE id = 123 UNION ALL SELECT id FROM users_archived WHERE id = 123;
SELECT GREATEST(@found := -1,id) AS id,‘users‘ AS which_tbl FROM users WHERE id = 1 UNION ALL SELECT id,‘users_archived‘ FROM users_archived WHERE id = 1 AND @found IS NULL UNION ALL SELECT 1,‘reset‘ FROM DUAL WHERE (@found := NULL) IS NOT NULL;
标签:过程 逻辑 mda 取出 如何 初始化 cto 读取 myisam
原文地址:http://www.cnblogs.com/uodut/p/7071118.html