日期:2014-05-16 浏览次数:20537 次
SELECT COL1,COL2 FROM T1;
SELECT TOP 300 COL1,COL2,COL3 FROM T1//因为某些情况下用户是不需要那么多的数据的。
SELECT name FROM employee WHERE salary > 60000
SELECT * FROM T1 WHERE F1/2=100 应改为: SELECT * FROM T1 WHERE F1=100*2 SELECT * FROM RECORD WHERE SUBSTRING(CARD_NO,1,4)=’5378’ 应改为: SELECT * FROM RECORD WHERE CARD_NO LIKE ‘5378%’ SELECT member_number, first_name, last_name FROM members WHERE DATEDIFF(yy,datofbirth,GETDATE()) > 21 应改为: SELECT member_number, first_name, last_name FROM members WHERE dateofbirth < DATEADD(yy,-21,GETDATE())即:任何对列的操作都将导致表扫描,它包括数据库函数、计算表达式等等,查询时要尽可能将操作移至等号右边。
SELECT id FROM employee WHERE id != 'B%'优化器将无法通过索引来确定将要命中的行数,因此需要搜索该表的所有行。
1.SELECT SUM(T1.C1)FROM T1 WHERE( (SELECT COUNT(*)FROM T2 WHERE T2.C2=T1.C2>0) 2.SELECT SUM(T1.C1) FROM T1WHERE EXISTS( SELECT * FROM T2 WHERE T2.C2=T1.C2)两者产生相同的结果,但是后者的效率显然要高于前者。因为后者不会产生大量锁定的表扫描或是索引扫描。
IF (SELECT COUNT(*) FROM table_name WHERE column_name = 'xxx') 可以写成: IF EXISTS (SELECT * FROM table_name WHERE column_name = 'xxx')
SELECT * FROM T1 WHERE NAME LIKE ‘%L%’ SELECT * FROM T1 WHERE SUBSTING(NAME,2,1)=’L’ SELECT * FROM T1 WHERE NAME LIKE ‘L%’即使NAME字段建有索引,前两个查询依然无法利用索引完成加快操作,引擎不得不对全表所有数据逐条操作来完成任务。
SELECT SUM(A.AMOUNT) FROM ACCOUNT A,CARD B WHERE A.CARD_NO = B.CARD_NO SELECT SUM(A.AMOUNT) FROM ACCOUNT A,CARD B WHERE A.CARD_NO = B.CARD_NO AND A.ACCOUNT_NO=B.ACCOUNT_NO第二句将比第一句执行快得多。
SELECT * FROM orders WHERE (customer_num=104 AND order_num>1001) OR order_num=1008解决办法可以使用并集来避免顺序存取:
SELECT * FROM orders WHERE customer_num=104 AND order_num>1001 UNION SELECT * FROM orders WHERE order_num=1008