2017-05-15 106 views
0

查询显示结果 - mysql的

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 
0

做到这一点的方法是添加虚拟列,然后使用分组将它们合并在一起。例如

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 
    ) 
) 

这仅适用于您的示例,因为您在查询的每个部分中始终只有一行,否则根本无法工作。

0

Union将两个表的结果作为一个结果集添加。连接将两个或更多表中的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 

测试1和测试2是我们一起加入这两个表的别名。

你有什么专栏可以加入吗?