日期:2014-05-16  浏览次数:20649 次

这两条语句哪条效率高?请说明原因
pre_threads 主题表(几千万的数据)
pre_forums 版块表

SQL code

SELECT t.tid,t.fid,t.subject,t.dateline FROM pre_threads t,pre_forums f WHERE f.fid=t.fid AND f.status IN(1,2) AND t.dateline>=unix_timestamp()-3600*24*3 LIMIT 5;

SELECT t.tid,t.fid,t.subject,t.dateline FROM pre_threads t,pre_forums f WHERE f.fid=t.fid AND f.status IN(1,2) ORDER BY t.dateline DESC LIMIT 5;



需求就是
第一条语句查询最近3天时间的5条数据;
第二条语句查询最新5条数据。


------解决方案--------------------
最直观的方法就是 你执行下 哪个用的时间短 哪个就效率高
------解决方案--------------------
explain SELECT t.tid,t.fid,t.subject,t.dateline 
FROM pre_threads t,pre_forums f 
WHERE f.fid=t.fid AND f.status 
IN(1,2) AND t.dateline>=unix_timestamp()-3600*24*3 LIMIT 5;

explain SELECT t.tid,t.fid,t.subject,t.dateline FROM pre_threads t,pre_forums f WHERE f.fid=t.fid AND f.status IN(1,2) ORDER BY t.dateline DESC LIMIT 5;
具体的执行计划看一下不就知道了。



------解决方案--------------------
************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: t
type: index
possible_keys: displayorder,typeid
key: pre_threads_index1
key_len: 4
ref: NULL
rows: 5
Extra:
*************************** 2. row ********


这个好
------解决方案--------------------
不一样的。
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: t
type: index
possible_keys: displayorder,typeid
key: pre_threads_index1
key_len: 4
ref: NULL
rows: 5
Extra:
*************************** 2. row ***************************
id: 1
select_type: SIMPLE
table: f
type: eq_ref
possible_keys: PRIMARY,forum
key: PRIMARY
key_len: 2
ref: tbl.t.fid
rows: 1
Extra: Using where
2 rows in set (0.00 sec)
此效率高。
------解决方案--------------------
看rows:执行的行数