eg:使用NorthWind示例数据库合并两个列:
select CustomerID from Customers
union
select CategoryID from Categories
用union实现这两个列的合并?
那位高手可以做到?
解决方法:
SQL code
select CustomerID from Customers
union
select cast(CategoryID as varchar) from Categories
用UNION,UNION ALL要确保3点:
1.第一个语句都要有列名
2.两个语句的列数要相等,不够要补足
3.所有对应列的类型要相同(或允许系统做隐式转化)
这样需要合并成一个VIEW就简单了:
create view v_all as
select CustomerID from Customers
union
select cast(CategoryID as varchar) from Categories
UNION用法:
MYSQL中的UNION
UNION在进行表链接后会筛选掉重复的记录,所以在表链接后会对所产生的结果集进行排序运算,删除重复的记录再返回结果。
举例说明:
select * from table1 union select * from table2
这个SQL在运行时先取出两个表的结果,再用排序空间进行排序删除重复的记录,最后返回结果集,如果表数据量大的话可能会导