当我执行此查询时:
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中我也是
select id as current
select id as previous
select id as next
他们都以current
???
任何想法?
答案 0 :(得分:2)
列名称相同的原因是,当您UNION
两个或多个查询时,最顶层查询中的列名称始终是最终结果中显示的名称,而不管后续查询中的列名(基本上被忽略)。
“第一个SELECT语句中的列名用作返回结果的列名。”
相反,为什么不在一个查询中的单独列中获取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
)
)
答案 1 :(得分:0)
工会不会那样工作。它们返回一组id,列名对于所有人都是相同的。
在您的具体情况下,运行3个单独的查询会更清楚。
答案 2 :(得分:0)
正如其他答案所指出的那样,不可能得到那个结果。
当我需要你所展示的内容时,我会包含一个文字作为标识符,显示哪个查询返回了值:
select 'current' as source, id from events where date = '{$result['date']}'
union all
(select 'previous', id from events
where date < '{$result['date']}' order by date desc limit 1)
union all
(select 'next', id from events
where date > '{$result['date']}' order by date asc limit 1)
返回的结果集与您的规范不符,但这种方法确实返回了我可以使用的结果。
这种方法避免了对数据库进行三次单独查询(语句分析,语句执行,语句提取)往返的(不必要的)开销。
这将为您提供类似这样的结构,您可以将其转换为所需的结构:
Array
(
[0] => Array
(
["source"] => "current"
["id"] => 6
)
[1] => Array
(
["source"] => "previous"
["id"] => 5
)
[2] => Array
(
["source"] => "next"
["id"] => 7
)
)