我是SQL
的新手,我在SQL
query
的表现方面遇到了一些问题。
我按照谷歌的一些观点创建了所需的indexes
。但仍然无法改善表现。
指导我提高遵循query
的效果。 tables
有数百万条记录。
SELECT TOP 15 id,
field1,
field2
FROM (SELECT DISTINCT 0 AS ID,
tblsuites.suite Field1,
'Work Order' AS Field2
FROM tbljb_schedules
INNER JOIN tblsuites
ON tbljb_schedules.tblsuites_id = tblsuites.tblsuites_id
INNER JOIN tblsites
ON tbljb_schedules.tblsites_id = tblsites.tblsites_id
LEFT OUTER JOIN tblbldgs
ON
tbljb_schedules.tblbldgs_id = tblbldgs.tblbldgs_id
WHERE tbljb_schedules.tbldomains_id = 28
AND tbljb_schedules.internalonly = 0
AND tbljb_schedules.tblsites_id IN (SELECT tblsites_id
FROM tbllogins_sites
WHERE tbllogins_id = 264
AND
tblsites.active = 1)
AND ( tblsuites.suite LIKE '%1%' )
UNION
SELECT DISTINCT 0 AS ID,
tblsuites.suite Field1,
'Work Order' AS Field2
FROM arcjb_schedules
INNER JOIN tblsuites
ON arcjb_schedules.tblsuites_id = tblsuites.tblsuites_id
INNER JOIN tblsites
ON arcjb_schedules.tblsites_id = tblsites.tblsites_id
LEFT OUTER JOIN tblbldgs
ON arcjb_schedules.tblbldgs_id =
tblbldgs. tblbldgs_id
WHERE arcjb_schedules.tbldomains_id = 28
AND arcjb_schedules.internalonly = 0
AND arcjb_schedules.tblsites_id IN (SELECT tblsites_id
FROM tbllogins_sites
WHERE tbllogins_id = 264
AND
tblsites.active = 1)
AND ( tblsuites.suite LIKE '%1%' )) T
ORDER BY CASE
WHEN Charindex('1', field1) = 1 THEN 0
ELSE 1
END,
field1
答案 0 :(得分:1)
也许您应该尝试以下代码更改
SELECT TOP 15
id,
field1,
field2
FROM
(
SELECT
0 AS ID,
tblsuites.suite Field1,
'Work Order' AS Field2,
SeqOne = CASE WHEN CHARINDEX('1', tblsuites.suite)= 1
THEN 1
ELSE 0 END
FROM tbljb_schedules
INNER JOIN tblsuites
ON tbljb_schedules.tblsuites_id = tblsuites.tblsuites_id
INNER JOIN tblsites
ON tbljb_schedules.tblsites_id = tblsites.tblsites_id
LEFT OUTER JOIN tblbldgs
ON tbljb_schedules.tblbldgs_id = tblbldgs.tblbldgs_id
WHERE tbljb_schedules.tbldomains_id = 28
AND tbljb_schedules.internalonly = 0
AND EXISTS -- Replace IN With EXISTS
(
SELECT
1
FROM tbllogins_sites
WHERE tbllogins_id = 264
AND tblsites.active = 1
AND tblsites_id = tbljb_schedules.tblsites_id
)
AND (tblsuites.suite LIKE '%1%')
UNION -- UNION Will By Default Take DISTINCT Records
SELECT
0 AS ID,
tblsuites.suite Field1,
'Work Order' AS Field2,
SeqOne = CASE WHEN CHARINDEX('1', tblsuites.suite)= 1
THEN 1
ELSE 0 END
FROM arcjb_schedules
INNER JOIN tblsuites ON arcjb_schedules.tblsuites_id = tblsuites.tblsuites_id
INNER JOIN tblsites ON arcjb_schedules.tblsites_id = tblsites.tblsites_id
LEFT OUTER JOIN tblbldgs ON arcjb_schedules.tblbldgs_id = tblbldgs.tblbldgs_id
WHERE arcjb_schedules.tbldomains_id = 28
AND arcjb_schedules.internalonly = 0
AND EXISTS
(
SELECT
1
FROM tbllogins_sites
WHERE tbllogins_id = 264
AND tblsites.active = 1
AND tblsites_id = arcjb_schedules.tblsites_id
)
AND (tblsuites.suite LIKE '%1%')
)T
ORDER BY
SeqOne,
field1;
答案 1 :(得分:0)
性能调优更像是一个反复试验的主题。
查看你的代码,我可以看到一个重要的性能罪犯。 where子句中的这个条件: 和tblsuites.suite LIKE'%1%'
我不知道tblSuites表有多大,但使用LIKE'%1%'会使优化器执行表扫描而不是索引查找,所以即使你已经索引该列也没用。
也按照@Jayasurya Satheesh在答案中提到的那样。