Union作为子查询的性能与单个查询的性能

时间:2019-02-27 02:47:43

标签: sql sql-server

我有一个这样的表:

CREATE TABLE [event] (
    id INT PRIMARY KEY IDENTITY (1,1),
    eventname1 nvarchar(50),
    eventname2 nvarchar(50),
    eventname3 nvarchar(50),
    eventname4 nvarchar(50),
    eventname5 nvarchar(50),
    eventname6 nvarchar(50),
    eventname7 nvarchar(50),
    eventname8 nvarchar(50),
    eventname9 nvarchar(50),
    eventname10 nvarchar(50),
    eventname11 nvarchar(50),
    eventname12 nvarchar(50)
);

然后我有这样的数据:

INSERT INTO [event] VALUES('1','1','1','1','1','1','1','1','1','1','1','1');
INSERT INTO [event] VALUES('2','2','2','2','2','2','2','2','2','2','2','2');
INSERT INTO [event] VALUES('3','3','3','3','3','3','3','3','3','3','3','3');
INSERT INTO [event] VALUES('4','4','4','4','4','4','4','4','4','4','4','4');
INSERT INTO [event] VALUES('5','5','5','5','5','5','5','5','5','5','5','5');
INSERT INTO [event] VALUES('6','6','6','6','6','6','6','6','6','6','6','6');

问题是哪种联合SQL更好:

1)

SELECT eventname1,del_flag FROM [event]   WHERE del_flag = '0' AND eventname1 LIKE '%1%'
UNION
SELECT eventname2 AS eventname1,del_flag FROM [event] WHERE del_flag = '0' AND eventname1 LIKE '%1%'
.....
SELECT eventname12,del_flag FROM [event]   WHERE del_flag = '0' AND eventname12 LIKE '%1%'

2)

SELECT * FROM 
(
    SELECT eventname1,del_flag FROM [event]
    UNION
    SELECT eventname2 AS eventname1,del_flag FROM [event] 
    ....
    SELECT eventname12 AS eventname1,del_flag FROM [event] 
) as [event]
WHERE del_flag = '0' AND eventname1 LIKE '%1%'

我已经看到了执行计划和实时查询静态数据。但这都是一样的。所以我不知道哪个更好。我曾考虑过取消查询,但性能似乎很慢。谁能解释一下哪个对大数据更好。

编辑1: 我正在寻找这样的输出

eventname
1 (eventname1)
2 (eventname2)
3 (eventname3)
4 (eventname4)
5 (eventname5)
6 (eventname6)

并且具有更好的性能

1 个答案:

答案 0 :(得分:0)

第一个稍微好一点,因为过滤发生在union之前。 union会删除重复项,从而产生开销。

一种更好的方法是取消数据透视:

SELECT DISTINCT v.eventname, e.del_flag
FROM event e CROSS APPLY
     (VALUES (eventname1), (eventname2), . . .
     ) v(eventname)
WHERE e.del_flag = 0 AND e.eventname LIKE '%1%';

这更好,因为它只需要读取一次表,而不是十二次。但是,删除重复项仍然会产生开销。