I need to write a SQL query to filter a table on 4 potential columns from another table of the filter values.
Example of what I am trying to do:
-- This table could have anywhere from 1 to 2000 possible rows
DECLARE @WidgetOwners TABLE (OwnerID INT PRIMARY KEY)
INSERT INTO @WidgetOwners VALUES (5)
INSERT INTO @WidgetOwners VALUES (50)
INSERT INTO @WidgetOwners VALUES (111)
INSERT INTO @WidgetOwners VALUES (12345)
INSERT INTO @WidgetOwners VALUES (6)
--etc...
SELECT w.WidgetID
FROM Widgets w
WHERE w.SellerManagerID IN (SELECT o.OwnerID FROM @WidgetOwners)
OR w.SellerID IN (SELECT o.OwnerID FROM @WidgetOw开发者_如何学编程ners)
OR w.BuyerManagerID IN (SELECT o.OwnerID FROM @WidgetOwners)
OR w.BuyerID IN (SELECT o.OwnerID FROM @WidgetOwners)
I am under the impression that the SUB SELECTS in the query above will not perform very well. Is there a better way to do this? Could this be done by LEFT JOINING the @WidgetOwner table multiple times? Does anyone have any recommendations here?
Keep in mind that I am stuck with SQL 2000 right now and cannot upgrade at the moment.
EDIT - Example 2 (This is something else I am trying)
SELECT w2.WidgetID, w2.* -- etc
FROM (
SELECT w.WidgetID
FROM Widgets w
INNER JOIN @WidgetOwners o ON w.SellerManagerID = o.OwnerID
UNION
SELECT w.WidgetID
FROM Widgets w
INNER JOIN @WidgetOwners o ON w.SellerID = o.OwnerID
UNION
SELECT w.WidgetID
FROM Widgets w
INNER JOIN @WidgetOwners o ON w.BuyerManagerID = o.OwnerID
UNION
SELECT w.WidgetID
FROM Widgets w
INNER JOIN @WidgetOwners o ON w.BuyerID = o.OwnerID
) x
INNER JOIN Widgets w2 ON x.WidgetID = w2.WidgetID
There are many rules of thumb in building efficient queries. But, I would suggest, when performance is a concern, it's always best to experiment with different approaches and to see in practice what performs best. Especially when row counts are large.
Suggest you try outer joins:
SELECT o1.ownerid, o2.ownerid, o3.ownerid, o4.ownserid
...
FROM widgets w
LEFT JOIN o AS o1 ON w.SellerManagerID = o.OwnerID
LEFT JOIN o AS o2 ON w.SellerID = o.OwnerID
LEFT JOIN o AS o3 ON w.BuyerManagerID = o.OwnerID
LEFT JOIN o AS o4 ON w.BuyerID = o.OwnerID
If helpful, (not knowing your requirement,) you can use
COALESCE(o1.OwnerID, o2.OwnerID, o3.ownerID, o4.ownerID)
or
CASE WHEN o1.ownerID IS NULL THEN ...
In my experience outer joins are nearly always as efficient as any other option, especially compared to correlated subqueries.
I also worry when you mention "temp table".
精彩评论