嘿伙计我有一些查询是由活动记录动态生成的,出于性能原因,我需要将它们合并在一起并一次性发送给MSSQL。
我尝试了以下内容,它在postgresql中运行良好,但我无法在MSSQL中使用它。
(SELECT [panels].* FROM [panels] WHERE [panels].[environment_id] = 14 AND [panels].[agglo_code_id] = 23 AND [panels].[advert_area_id] = 161 AND [panels].[product_id] = 25 AND (NOT EXISTS(SELECT 1 FROM campaign_search_panels WHERE campaign_search_panels.panel_id = panels.panel_id AND campaign_search_panels.campaign_id = 65)) AND (NOT EXISTS(SELECT 1 FROM "AIDAAU_Avails" WHERE "AIDAAU_Avails"."PanelID" = panels.panel_uid AND "AIDAAU_Avails"."TillDate" >= '08-21-2017' AND "AIDAAU_Avails"."FromDate" <= '09-03-2017')) ORDER BY [panels].[random_order] ASC OFFSET 0 ROWS FETCH NEXT 3 ROWS ONLY)
UNION ALL
(SELECT [panels].* FROM [panels] WHERE [panels].[environment_id] = 14 AND [panels].[agglo_code_id] = 23 AND [panels].[advert_area_id] = 136 AND [panels].[product_id] = 25 AND (NOT EXISTS(SELECT 1 FROM campaign_search_panels WHERE campaign_search_panels.panel_id = panels.panel_id AND campaign_search_panels.campaign_id = 65)) AND (NOT EXISTS(SELECT 1 FROM "AIDAAU_Avails" WHERE "AIDAAU_Avails"."PanelID" = panels.panel_uid AND "AIDAAU_Avails"."TillDate" >= '08-21-2017' AND "AIDAAU_Avails"."FromDate" <= '09-03-2017')) ORDER BY [panels].[random_order] ASC OFFSET 0 ROWS FETCH NEXT 2 ROWS ONLY)
现在我认为我已经发现了两个问题。如果我删除每个查询周围的括号,那么我靠近但它仍然抱怨ORDER。我有一种感觉,你只能在结果之后订购,但我不能控制每个单独的SQL查询如何组合在一起,只考虑我如何组合它们。理想情况下,我希望保持订单的能力,并为每个子查询设置限制条款。是否有任何简单的方法将它们组合在一起,以便它们可以在MSSQL中工作而不仅仅是postgres?
感谢您的帮助!
答案 0 :(得分:1)
在UNION查询中,您只能有一个ORDER BY子句,它必须在最后:
SELECT * from <table1>
UNION ALL
SELECT * from <table2>
ORDER BY <col1>
您必须在顶部查询中删除该ORDER BY,它才能正常工作
答案 1 :(得分:0)
如果要订购联合结果,则必须将结果放入CTE。像这样:
with cte_name as
(
select col_1, col_2, etc
from table
union all
select col_1, col_2, etc
from table_2
)
select col_1, col_2
from cte_name
order by col_1