SQL SELECT Union SELECT FROM (Select…)

2019-08-02 13:38发布

问题:

I'm working with a view, and can't use temp tables. Is it possible to :

SELECT * FROM table1 UNION SELECT * FROM (SELECT * FROM table 3)

I realize its bad coding practice select *, I'm just using it as an example. Any help would be appreciated!

回答1:

That query parses as:

(SELECT * FROM table1)
UNION
(SELECT * FROM (SELECT * FROM table 3))

In SQL Server, this will return a missing alias error. So, add in the alias:

(SELECT * FROM table1)
UNION
(SELECT * FROM (SELECT * FROM table 3) t)


回答2:

Yes.

if there has same count's of columns.. it will work

or try to these code

SELECT A.COL1, A.COL2 FROM TABLE1 A 

UNION 

SELECT B.COL1, B.COL2 FROM (SELECT C.COL1, C.COL2 FROM TABLE3)


回答3:

I was wondering why you need to wrap it in a subquery, isn't it possible to do it directly<

SELECT * FROM table1
UNION
SELECT * FROM table3