使用多个联合优化查询性能
Posted
技术标签:
【中文标题】使用多个联合优化查询性能【英文标题】:Optimize query performance with multiple union 【发布时间】:2019-08-16 05:30:47 【问题描述】:我的要求是在选定的表格中搜索特定的文本。
但是对于某些列,所有表的结构都不同,我需要使用连接多个表来使用 ID 进行搜索,而对于某些列,我可以直接搜索数据
我可以使用下面的查询来实现上述要求,但是有什么方法可以优化查询并缩短查询时间
SELECT A.id,
Concat(A.fname, ' ', A.lname) AS NAME,
A.category
FROM dbo.employeedetail A
LEFT JOIN dbo.combovalues B
ON A.department = B.id
LEFT JOIN dbo.combovalues C
ON A.designation = C.id
LEFT JOIN dbo.combovalues D
ON A.esilocation = D.id
LEFT JOIN dbo.combovalues E
ON A.grade = E.id
LEFT JOIN dbo.combovalues F
ON A.costcentre = F.id
LEFT JOIN dbo.combovalues G
ON A.branch = G.id
LEFT JOIN dbo.combovalues H
ON A.location = H.id
LEFT JOIN dbo.combovalues I
ON A.esidispensary = I.id
LEFT JOIN dbo.combovalues J
ON A.ptlocation = J.id
WHERE ( code LIKE '%maharashtra%'
OR fname LIKE '%maharashtra%'
OR lname LIKE '%maharashtra%'
OR mname LIKE '%maharashtra%'
OR fathername LIKE '%maharashtra%'
OR gender LIKE '%maharashtra%'
OR maritalstatus LIKE '%maharashtra%'
OR pfaccno LIKE '%maharashtra%'
OR esino LIKE '%maharashtra%'
OR panno LIKE '%maharashtra%'
OR metro LIKE '%maharashtra%'
OR address1 LIKE '%maharashtra%'
OR address2 LIKE '%maharashtra%'
OR place LIKE '%maharashtra%'
OR city LIKE '%maharashtra%'
OR pincode LIKE '%maharashtra%'
OR phoneno LIKE '%maharashtra%'
OR corr_address1 LIKE '%maharashtra%'
OR corr_address2 LIKE '%maharashtra%'
OR corr_place LIKE '%maharashtra%'
OR corr_city LIKE '%maharashtra%'
OR corr_phone LIKE '%maharashtra%'
OR corr_pincode LIKE '%maharashtra%'
OR email LIKE '%maharashtra%'
OR personalemail LIKE '%maharashtra%'
OR personalmobileno LIKE '%maharashtra%'
OR officemobileno LIKE '%maharashtra%'
OR uannumber LIKE '%maharashtra%'
OR B.combovalue LIKE '%maharashtra%'
OR C.combovalue LIKE '%maharashtra%'
OR D.combovalue LIKE '%maharashtra%'
OR E.combovalue LIKE '%maharashtra%'
OR F.combovalue LIKE '%maharashtra%'
OR G.combovalue LIKE '%maharashtra%'
OR H.combovalue LIKE '%maharashtra%'
OR I.combovalue LIKE '%maharashtra%'
OR J.combovalue LIKE '%MAHARASHTRA%' )
UNION
SELECT A.employeeid,
Concat(D.fname, ' ', D.lname) AS NAME,
D.category
FROM dbo.customefielddetail A
LEFT JOIN dbo.employeeconfig C
ON A.customefieldname = C.fieldname
AND C.dfield = 'N'
AND C.celltype = 'D'
LEFT JOIN dbo.combovalues B
ON A.fieldvalue = Cast(B.id AS NVARCHAR(max))
AND B.fieldname = B.fieldname
LEFT JOIN dbo.employeedetail D
ON A.employeeid = D.id
WHERE B.combovalue LIKE '%maharashtra%'
UNION
SELECT A.employeeid,
Concat(D.fname, ' ', D.lname) AS NAME,
D.category
FROM dbo.customefielddetail A
LEFT JOIN dbo.employeedetail D
ON A.employeeid = D.id
WHERE A.fieldvalue LIKE '%maharashtra%'
【问题讨论】:
您的like
条件不能使用索引。您是否在相关列上有全文索引,如果有,您可以使用 CONTAINS 查询。那么它应该真的很快
@juergend 全文搜索未启用
【参考方案1】:
您可以轻松实现的第一个优化是将UNION
替换为UNION ALL
。请记住,UNION
隐式删除重复行。因此,如果您确信不会得到任何重复值,那么这种替换应该是一个很好的优化。
希望对你有帮助!
【讨论】:
以上是关于使用多个联合优化查询性能的主要内容,如果未能解决你的问题,请参考以下文章
多个连接和联合的查询性能真的很差,有没有其他方法可以提高执行时间?