过滤联合结果

时间:2010-10-29 10:13:29

标签: tsql sql-server-2008

我正在选择工会。 select * from table_1 union select * from table_2 ...

是否可以按列值过滤查询结果?

3 个答案:

答案 0 :(得分:10)

是的,您可以将整个联盟包含在另一个选择中:

select * from (
select * from table_1 union select * from table_2) as t
where t.column = 'y'

您必须引入表的别名(“as t”)。此外,如果表中的数据是不相交的,您可能需要考虑切换到UNION ALL - UNION本身可以消除结果集中的重复项。这通常没有必要。

答案 1 :(得分:2)

如果您想根据某些条件过滤查询,那么您可以这样做 -

Select * from table_1 where table_1.col1 = <some value>
UNION
Select * from table_2 where table_2.col1 = <some value>

但是,我想说如果你想过滤结果来找到常用值,那么你可以使用连接代替

Select * from table_1 inner join table_2 on table_1.col1 = table_2.col1

答案 2 :(得分:1)

简单易懂的解决方案是使用CTE(公用表表达式)。采用以下形式:

WITH foobar AS (
    SELECT foo, bar FROM table_1
    UNION
    SELECT foo, bar FROM table_2
)

然后,您可以按名称在后续查询中引用CTE,就像它是普通表一样:

SELECT foo,bar FROM foobar WHERE foo = 'value'

CTE非常强大,我建议进一步阅读here

您在MS文章中找不到的一个提示是;如果您需要多个CTE,请在表达式语句之间添加逗号。例如:

WITH foo AS (
    SELECT thing FROM place WHERE field = 'Value'
),
bar AS (
    SELECT otherthing FROM otherplace WHERE otherfield = 'Other Value'
)