UNION 语句相同的选定值 - 奇怪的行为 [重复]

Posted

技术标签:

【中文标题】UNION 语句相同的选定值 - 奇怪的行为 [重复]【英文标题】:UNION Statement Same Selected Values - Strange Behavior [duplicate] 【发布时间】:2014-10-14 16:55:55 【问题描述】:

我在具有相同值的 UNIONed select 语句中发现了一个非常奇怪的行为。

试图在网络上查找发生了什么,但不知道如何表达对这个问题的搜索,需要解释,如下:

测试 1:

SELECT 
        ID, SUM(AMT) AS AMT
    FROM
    (
        SELECT 1 AS ID, 100 AS AMT FROM DUAL UNION
        SELECT 1 AS ID, 100 AS AMT FROM DUAL UNION
        SELECT 1 AS ID, 100 AS AMT FROM DUAL UNION
        SELECT 1 AS ID, 100 AS AMT FROM DUAL
    )
    GROUP BY ID; 

测试 2:

SELECT 1 AS ID, 100 AS AMT FROM DUAL UNION
SELECT 1 AS ID, 100 AS AMT FROM DUAL UNION
SELECT 1 AS ID, 100 AS AMT FROM DUAL UNION
SELECT 1 AS ID, 100 AS AMT FROM DUAL;

所有这些选择语句都给出相同的结果:

所以,假设我正在编写一个动态代码,在运行时在我的一个应用程序中生成和执行,而代码恰好如上所示!如何使这个 select 语句起作用?

【问题讨论】:

你追求的是 UNION ALL 吗? 谢谢,现在对我有意义 【参考方案1】:

请尝试以下一个

SELECT 1 AS ID, 100 AS AMT FROM DUAL UNION all

SELECT 1 AS ID, 100 AS AMT FROM DUAL UNION all

SELECT 1 AS ID, 100 AS AMT FROM DUAL UNION all

SELECT 1 AS ID, 100 AS AMT FROM DUAL;

【讨论】:

【参考方案2】:

您可以尝试使用 UNION ALL

SELECT 
        ID, SUM(AMT) AS AMT
    FROM
    (
        SELECT 1 AS ID, 100 AS AMT FROM DUAL UNION ALL
        SELECT 1 AS ID, 100 AS AMT FROM DUAL UNION ALL
        SELECT 1 AS ID, 100 AS AMT FROM DUAL UNION ALL
        SELECT 1 AS ID, 100 AS AMT FROM DUAL
    )
    GROUP BY ID; 

【讨论】:

以上是关于UNION 语句相同的选定值 - 奇怪的行为 [重复]的主要内容,如果未能解决你的问题,请参考以下文章

UNION和UNION ALL

union 和 union all区别

SQL UNION 的用法中前后两个查询语句所含字段是不是一定要相同?

UNION 和 UNION ALL 操作符

iOS7 中选定 UITableViewCell 的奇怪行为

union连接的两个表的字段必须完全相同吗?