UNIONALL花费更多时间,下面是查询示例。如下面提到的表T1仅有4条记录,但在我的查询中,T1有近150万条记录。 有没有办法调整下面的查询意味着unionall我们可以使用任何条件。谢谢!
CREATE TABLE T1 (ID INT, FROM_KEY INT,TO_KEY INT, IS_STATUS BIT)
INSERT INTO T1 VALUES(1, 50001,50002, 1)
INSERT INTO T1 VALUES(2, 50003,50004, 1)
INSERT INTO T1 VALUES(3, 50005,50006, 1)
INSERT INTO T1 VALUES(4, 50007,50008, 1)
DECLARE @KEY INT = 50002
SELECT TO_KEY FROM T1 WHERE TO_KEY=@KEY AND IS_STATUS=1
UNION ALL
SELECT FROM_KEY FROM T1 WHERE FROM_KEY=@KEY AND IS_STATUS=1
答案 0 :(得分:1)
可以简化为:
SELECT @KEY
FROM T1
WHERE @KEY IN (TO_KEY, FROM_KEY)
AND IS_STATUS = 1
(如果to_key和from_key同时等于@key,则只返回同一行,而UNION ALL查询将返回该行两次。)
答案 1 :(得分:0)
单次通过查询可能更加优化:
SELECT CASE WHEN N=0 THEN FROM_KEY ELSE TO_KEY END
FROM (SELECT * FROM T1 WHERE @KEY in (TO_KEY, FROM_KEY) AND IS_STATUS=1) AS A
JOIN (SELECT 0 N UNION ALL SELECT 1) AS B
ON (N=0 AND TO_KEY=@KEY) OR (N=1 AND FROM_KEY=@KEY)
但总的来说,如果您希望获得有关查询优化的帮助,您必须提供有关sql server品牌,版本,数据大小,索引等的更多信息。