mysql UNION 命名表属性

标签 mysql sql union

当我执行此查询时:

select id as current from events where date = '{$result['date']}'
union all
(select id as previous from events where date < '{$result['date']}' order by date desc limit 1)
union all
(select id as next from events where date > '{$result['date']}' order by date asc limit 1)

它选择日期为 $result['date] 的 ID、低于该日期的日期以及高于该日期的日期。

所以在我的 php 代码中我需要一个像这样的数组:

Array
(
    [0] => Array
    (
        [current] => 6
    )

    [1] => Array
    (
        [previous] => 5
    )

    [2] => Array
    (
        [next] => 7
    )

)

然而,数组的结果是这样的:

Array
(
    [0] => Array
    (
        [current] => 6
    )

    [1] => Array
    (
        [current] => 5
    )

    [2] => Array
    (
        [current] => 7
    )

)

我需要 assoc 数组来描述正确的键!

尽管在我的 SQL 中我这样做

选择 ID 作为当前 选择 id 作为上一个 选择 id 作为下一个

它们都是当前???

有什么想法吗?

最佳答案

之所以该列同名是因为当你 UNION两个或多个查询中,最上面的查询中的列名始终是最终结果中显示的名称,而不管后续查询中的列名如何(它们基本上会被忽略)。

MySQL Union Syntax

"The column names from the first SELECT statement are used as the column names for the results returned."


相反,为什么不在一个查询中的单独列中获取 ID?

SELECT a.id AS current, prev.id AS previous, next.id AS next
FROM events a
CROSS JOIN 
(
    SELECT id FROM events 
    WHERE date < '{$result['date']}' 
    ORDER BY date DESC 
    LIMIT 1
) prev
CROSS JOIN 
(
    SELECT id
    FROM events 
    WHERE date > '{$result['date']}' 
    ORDER BY date 
    LIMIT 1
) next
WHERE a.date = '{$result['date']}'

这会给你类似的东西:

Array
(
    [0] => Array
    (
        [current] => 6
        [previous] => 5
        [next] => 7
    )
)

关于mysql UNION 命名表属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11468295/

相关文章:

SQL 将子查询 'Total Records' 返回给外部查询

mysql - 如何在 SET 子查询中引用外表?

mysql - 设计公司->所在位置->产品数据库

algorithm - 联合的时间复杂度

SQL聚合多个表的数据并对指定列求和

MySQL 一个查询中的多个联接?

php - Doctrine 和 Symfony 中的 MySQL 用户定义变量

mysql - MySQL 中何时使用单引号、双引号和反引号