[英]Optimizing query to improve performance
How to optimize the following SQL query? 如何优化以下SQL查询? I have this query which works but I need to optimize it, or do you have a suggestion for an online SQL refactoring tool? 我有这个查询,但我需要对其进行优化,或者您对在线SQL重构工具有何建议?
Table: Membership
表: Membership
+---------+--------+
| GroupID | UserID |
+---------+--------+
| 123 | 605 |
| 124 | 605 |
| 125 | 605 |
| 123 | 606 |
| 125 | 606 |
| 124 | 607 |
+---------+--------+
Table: content_group_membership
表: content_group_membership
+---------+-----------+
| GroupID | ContentId |
+---------+-----------+
| 11111 | 123 |
| 22222 | 123 |
| 44444 | 124 |
| 22222 | 125 |
| 11111 | 126 |
| 33333 | 126 |
| 11111 | 125 |
+---------+-----------+
The Membership
table holds the list of groupID
the user belongs to and the content_group_membership
table hold the list of permitted ContentID
for the corresponding groupID
. Membership
表保存用户所属的groupID
列表, content_group_membership
表保存相应groupID
的允许ContentID
列表。
We need to get the list of contentID
which are restricted for that user, groupID
for the UserID
should be taken from Membership
table and the contentID
with groupID
of other than user's groupID
are restricted ContentID
for that UserID
. 我们需要得到的名单contentID
这是该用户的限制, groupID
的UserID
应采取Membership
表和contentID
与groupID
的以外用户groupID
仅限ContentID
该UserID
。
Below is the query, right now we are using which is consuming triple the amount of time consumed to fetch the result when the below query is used as sub query. 下面是查询,现在我们正在使用的查询将以下查询用作子查询时所花费的时间是获取结果的三倍。 So, we want an optimized query to fetch results quickly. 因此,我们希望优化查询能够快速获取结果。
Expected result : 33333 预期结果:33333
Query: 查询:
SELECT DISTINCT
[ContentID], groupid
FROM
[content_group_membership]
WHERE
contentid NOT IN (SELECT [ContentID]
FROM [content_group_membership]
WHERE GroupID IN (SELECT groupid
FROM Membership
WHERE UserID = 605 ))
AND GroupID IN (SELECT GroupID
FROM [content_group_membership]
WHERE groupid NOT IN (SELECT groupid
FROM Membership
WHERE UserID = 605))
This should be equivalent, and run more efficiently: 这应该等效,并且运行效率更高:
SELECT DISTINCT [ContentID],
groupid
FROM [content_group_membership]
WHERE contentid != ANY (SELECT [ContentID]
FROM [content_group_membership]
WHERE GroupID IN (SELECT groupid
FROM Membership
WHERE UserID = 605
AND Active = 1))
AND GroupID NOT IN (SELECT groupid
FROM Membership
WHERE UserID = 605
AND Active = 1))
However, a query of this complexity might be better off as a procedure. 但是,这种过程的查询可能更好。
I don't have enough reputions to comment, so, it will do this as an answer. 我没有足够的声誉来发表评论,因此,它将作为答案。
I believe this query is primed for a CTE so it doesn't have to executed twice. 我相信此查询是为CTE准备的,因此不必执行两次。
http://technet.microsoft.com/en-us/library/ms186243(v=SQL.105).aspx http://technet.microsoft.com/zh-cn/library/ms186243(v=SQL.105).aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.