select a.名称1 from 表1 a where 条件1 union select b.名称2 from 表1 b where 条件2
select a.名称1 from 表1 a where 条件1 union select b.名称2 from 表1 b where 条件2 select a.名称1 from 表1 a where 条件1 union all select b.名称2 from 表1 b where 条件2
难道楼上是全才???我过几天要搞一个基于sql server2005的数据挖掘, 大哥可要指点下啊
UNION会消除重复行,UNION ALL 不会~ 所以用UNION ALL会效率高不少~
用union之前必须确认一下你的2个表对应的字段个数和字段类型是否一致
select a.名称 as 显示字段1,a.姓名 from 查询表 a where 条件1select b.名称 as 显示字段2,b.姓名 from 查询表 b where 条件2两个名称在统计的时候,可能有所不同,表中字段是一样的我就是那样用union连接的,出来的查询结果还不是想要的要显示: 姓名 显示字段1 显示字段2 aa 48 60 要这样的效果
select A.姓名,A.显示字段1,B.显示字段2 FROM 表1 A inner join 表1 B ON A.姓名=B.姓名
我上面用姓名关联只是打个比方~~ 你还可以在后面加WHERE 写限制条件
select a.名称1 from 表1 a where 条件1 select b.名称2 from 表1 b where 条件2 两个语句的表相同,现在想用union将两个语句联合起来,而且显示出来名称1和名称2,两条语句的查询条件有点不同 是同一个表为什么要2个查询条件union呢? select case when 条件1 then c.名称1 else c.名称2 end as 名称 from 1 c where 条件1 or 条件2 这个速度比union all 都要快。
select a.名称1 from 表1 a
where 条件1
union
select b.名称2 from 表1 b
where 条件2
where 条件1
union
select b.名称2 from 表1 b
where 条件2
select a.名称1 from 表1 a
where 条件1
union all
select b.名称2 from 表1 b
where 条件2
大哥可要指点下啊
所以用UNION ALL会效率高不少~
姓名 显示字段1 显示字段2
aa 48 60
要这样的效果
select A.姓名,A.显示字段1,B.显示字段2 FROM 表1 A inner join 表1 B ON A.姓名=B.姓名
你还可以在后面加WHERE 写限制条件
where 条件1
select b.名称2 from 表1 b
where 条件2 两个语句的表相同,现在想用union将两个语句联合起来,而且显示出来名称1和名称2,两条语句的查询条件有点不同
是同一个表为什么要2个查询条件union呢?
select
case when 条件1 then c.名称1
else c.名称2 end as 名称
from 1 c
where 条件1
or 条件2
这个速度比union all 都要快。