查询
select
min(temperature) as minTemp,
max(temperature) as maxTemp from test
union
(
select
temperature as Temp ,
datetime as Date
from test
order by datetime desc
limit 1
)
返回结果:
+---------+---------------------+
| minTemp | maxTemp |
+---------+---------------------+
| 24.11 | 26.739999771118164 |
| 25.93 | 2017-05-14 15:11:09 |
+---------+---------------------+
如何在单独的列中显示结果,如:
+---------+---------------------+----------+----------------------+
| minTemp | maxTemp | Temp |Date |
+---------+---------------------+----------+----------------------+
| 24.11 | 26.739999771118164 | 25.93 | 2017-05-14 15:11:09 |
| | | | |
+---------+---------------------+----------+----------------------+
答案 0 :(得分:1)
我认为在这种情况下CROSS JOIN
是你的朋友。你可以这样做:
select
min(temperature) as minTemp,
max(temperature) as maxTemp,
t.Temp,
t.Date
from
test
CROSS JOIN
(
select
t1.temperature as Temp ,
t1.datetime as Date
from
test as t1
order by
t1.datetime desc
limit 1
) as t
答案 1 :(得分:0)
这样做的方法是添加虚拟列,然后使用分组将它们合并在一起。 e.g。
Select max(minTemp),max(maxTemp),max(Temp),max(Date) from (
select
min(temperature) as minTemp,
max(temperature) as maxTemp from test , null as Temp, Null as Date
union
(
select null as minTemp, null as maxtemp,
temperature as Temp ,
datetime as Date
from test
order by datetime desc
limit 1
)
)
这仅适用于您的示例,因为您在查询的每个部分中始终只有一行,否则它根本不起作用。
答案 2 :(得分:0)
Union将两个表的结果ROWS添加为一个结果集。 Join将两个或多个表中的COLUMNS作为一行添加。因此,在这种情况下,加入可能是更好的选择。
然而,为了使这项工作,你需要有一些东西可以加入,例如id或确切的日期或类似的东西。因为我不知道你是否有这个是一个示例SQL:
select
min(test1.temperature) as minTemp,
max(test1.temperature) as maxTemp,
test2.temperature as Temp,
test2.datetime as Date
from test test1 join test test2
on _something_that_you_can_join_on_
order by datetime desc limit 1
test1和test2是我们连接在一起的两个表的别名。
您是否有可以加入的专栏?