简体   繁体   English

SQL-UNION,在执行以下命令时优先于第一个选择语句

[英]SQL - UNION, priority on the first select statement when doing order by

I'm trying to print out the results from the "GermanDB" Database first, while also showing everything from the Boston DB that was not in the German database. 我试图首先从“ GermanDB”数据库中打印出结果,同时还显示来自Boston DB的所有德语数据库中未包含的内容。 Can this be done in one query? 可以在一个查询中完成吗?

My query (the bold part functions but does not order the way I want) 我的查询(粗体部分起作用,但未按我想要的方式排序)

select * from (  
SELECT DISTINCT a.ProductRef  
FROM GERMANDB.dbo.LOCATIONS AS a INNER JOIN GERMANDB.dbo.ITEMS AS b ON a.ProductRef =   b.ProductRef   
WHERE b.ACTIVE=1  
) ta  
UNION select * from  
SELECT DISTINCT c.ProductRef  
FROM BOSTONDB.dbo.LOCATIONS AS c INNER JOIN BOSTONDB.dbo.ITEMS AS d ON c.ProductRef =   d.ProductRef   
WHERE c.ACTIVE=1 (c.ProductRef NOT IN   
(SELECT ProductRef FROM GERMANDB.dbo.ITEMS where ACTIVE=1))  
) tb  
order by ta.ProductRef** , tb.productRef

Just add one field to signal the priority. 只需添加一个字段即可发出优先级信号。 Like this: 像这样:

select *, 0 as Priority from (  
SELECT DISTINCT a.ProductRef  
FROM GERMANDB.dbo.LOCATIONS AS a INNER JOIN GERMANDB.dbo.ITEMS AS b ON a.ProductRef =   b.ProductRef   
WHERE b.ACTIVE=1  
) ta  
UNION select *, 1 as Priority from  
SELECT DISTINCT c.ProductRef  
FROM BOSTONDB.dbo.LOCATIONS AS c INNER JOIN BOSTONDB.dbo.ITEMS AS d ON c.ProductRef =   d.ProductRef   
WHERE c.ACTIVE=1 (c.ProductRef NOT IN   
(SELECT ProductRef FROM GERMANDB.dbo.ITEMS where ACTIVE=1))  
) tb  
order by Priority, ProductRef

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM