T-SQL是需要优化的。而优化的前提是你对它的执行步骤有清楚的认识。我经常去给讲课或者咨询辅导的时候,就发现很多朋友对此了解甚少。下面截取了我的一个PPT,给大家参考一下 下面这个脚本可以解释这个过程 /* 这个脚本用来帮助用户理解T-SQL查询的逻辑顺序和原理。 作者:陈希章 */ /* 准备数据架构和数据 */ SET NOCOUNT ON. USE tempdb. GO IF OBJECT_ID( dbo.Orders ) IS NOT NULL DROP TABLE dbo.Orders. GO IF OBJECT_ID( dbo.Customers ) IS NOT NULL DROP TABLE dbo.Customers. GO CREATE TABLE dbo.Customers ( customerid CHAR(5) NOT NULL PRIMARY KEY, city VARCHAR(10) NOT NULL ). INSERT INTO dbo.Customers(customerid, city) VALUES( FISSA , Madrid ). INSERT INTO dbo.Customers(customerid, city) VALUES( FRNDO , Madrid ). INSERT INTO dbo.Customers(customerid, city) VALUES( KRLOS , Madrid ). INSERT INTO dbo.Customers(customerid, city) VALUES( MRPHS , Zion ). CREATE TABLE dbo.Orders ( orderid INT NOT NULL PRIMARY KEY, customerid CHAR(5) NULL REFERENCES Customers(customerid) ). INSERT INTO dbo.Orders(orderid, customerid) VALUES(1, FRNDO ). INSERT INTO dbo.Orders(orderid, customerid) VALUES(2, FRNDO ). INSERT INTO dbo.Orders(orderid, customerid) VALUES(3, KRLOS ). INSERT INTO dbo.Orders(orderid, customerid) VALUES(4, KRLOS ). INSERT INTO dbo.Orders(orderid, customerid) VALUES(5, KRLOS ). INSERT INTO dbo.Orders(orderid, customerid) VALUES(6, MRPHS ). INSERT INTO dbo.Orders(orderid, customerid) VALUES(7, NULL). /* 一个测试查询,检索那些订单个数小于3的客户,并且按订单总数排序(升序) */