当我执行此查询时:
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
block 引用>"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/