我得到两个union子句的结果。我消除了不同的重复行。但我必须保持第一行,但明显消除第一行。我如何保留第一行?
//for example in this sql first i have expected PRodId=10 first but it is last.
SELECT DISTINCT * FROM (
SELECT ProdId FROM Products WHERE ProdId=10
UNION ALL
SELECT ProdId FROM Products WHERE ProdId=120
UNION ALL
SELECT ProdId FROM Products WHERE ProdId=400
UNION ALL
SELECT ProdId FROM Products WHERE ProdId=10) prods
答案 0 :(得分:2)
为什么联盟全部?
Select Distinct ProdId
From Products
Where ProdId in (10,120,400)
Order By ProdID
答案 1 :(得分:0)
按产品ID排序,如果这是您首先期望10的原因..除非您提供order by
子句,否则无法保证sql查询结果的顺序。
SELECT DISTINCT * FROM (
SELECT ProdId FROM Products WHERE ProdId=10
UNION ALL
SELECT ProdId FROM Products WHERE ProdId=120
UNION ALL
SELECT ProdId FROM Products WHERE ProdId=400
UNION ALL
SELECT ProdId FROM Products WHERE ProdId=10) prods
ORDER BY prods.ProdId
答案 2 :(得分:0)
如果您想要特定顺序的行,那么您需要在查询中包含order by
。在您的情况下,您可以添加:
order by (case prodid when 10 then 1 when 120 then 2 when 400 then 3 end)
您可以将整个查询编写为:
select distinct p.prodid
from products p
where prodid in (10, 120, 400)
order by (case prodid when 10 then 1 when 120 then 2 when 400 then 3 end);
两个注释:
select distinct
。order by prodid
。答案 3 :(得分:0)
如果没有显式的ORDER BY,返回给应用程序的结果集中的行顺序与数据源的排序(表表达式)无关。查询优化器可以按照“认为”更快的任何顺序自由返回行。 在查询中提供显式ORDER BY。