【问题标题】:Combining two SQL SELECT statements on the same table在同一个表上组合两个 SQL SELECT 语句
【发布时间】:2014-03-22 08:33:59
【问题描述】:

我想结合这两个 SQL 查询:

SELECT * FROM "Contracts" WHERE 
"productType" = 'RINsell' AND
"clearTime" IS NULL AND
"holdTime" IS NOT NULL 
 ORDER BY "generationTime";

SELECT * FROM "Contracts" WHERE 
"productType" = 'RINsell' AND
"clearTime" IS NULL AND
"holdTime" IS NULL 
 ORDER BY "contractLimitPrice";

当我运行每条语句时,我得到的正是我想要的结果,我希望这两个结果都按顺序排列。我的第一个想法是使用 UNION ALL,因为这个选择会不相交,但我发现你不能在 ORDER BY 之后使用 UNION。我搜索了很多,大多数人建议在UNION 之后执行ORDER BY,但每个查询都有不同的ORDER BY 条件。

【问题讨论】:

  • 你试过 SELECT (query1) UNION ALL (query2) 吗?
  • 我不关注;喜欢:SELECT( * FROM "Contracts" WHERE "productType" = 'RINsell' AND "clearTime" IS NULL AND "holdTime" IS NOT NULL ORDER BY "generationTime") UNION ALL SELECT( * FROM "Contracts" WHERE "productType" = 'RINsell' AND "clearTime" IS NULL AND "holdTime" IS NULL ORDER BY "contractLimitPrice");

标签: sql database postgresql sql-order-by union


【解决方案1】:

如果您希望第一个查询的结果在第二个查询的结果之前,您可以从 where 子句中删除 holdtime,并使用按赞排序

order by
  case when holdTime is not null then 0 else 1 end, --first query comes first
  case when holdTime is not null --different orders for queries
       then generationTime
       else contractLimitPrice
  end

【讨论】:

  • 谢谢!我以前从来没有用 SQL 做过任何事情,所以我花了一秒钟才弄明白:SELECT * FROM "Contracts" WHERE "productType" = 'RINsell' AND "clearTime" IS NULL order by case when "holdTime" is not null then 0 else 1 end, --first query comes first case when "holdTime" is not null --different orders for queries then "generationTime" else "contractLimitPrice" end;
【解决方案2】:

...但我发现你不能在ORDER BY 之后使用UNION

好吧,你看起来不够努力:

(
SELECT *
FROM   "Contracts"
WHERE  "productType" = 'RINsell'
AND    "clearTime" IS NULL
AND    "holdTime" IS NOT NULL 
ORDER  BY "generationTime"
)
UNION ALL
)
SELECT *
FROM   "Contracts"
WHERE  "productType" = 'RINsell'
AND    "clearTime" IS NULL
AND    "holdTime" IS NULL 
ORDER  BY "contractLimitPrice"
)

注意括号。 Per documentation:

(ORDER BYLIMIT 可以附加到子表达式,如果它是 括在括号中。没有括号,这些子句将是 应用于UNION 的结果,而不是应用于其右侧输入 表达。)

密切相关的答案:
Sum results of a few queries and then find top 5 in SQL

旁白:我真的会get rid of those CaMeL case identifiers。使用 Postgres 中的全小写合法标识符,您的生活会轻松得多。

【讨论】:

    猜你喜欢
    • 2013-05-31
    • 2017-07-14
    • 2010-11-24
    • 1970-01-01
    • 2018-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    相关资源
    最近更新 更多