结合MySQL查询

时间:2018-02-17 17:16:49

标签: mysql sql

这个SQL告诉我在最后一小时内发生的最大值是多少,并且很容易被修改为显示相同的最小值。

SELECT
  mt.mB as Hr_mB_Max,
  mt.UTC as Hr_mB_Max_when
FROM
  thundersense mt
WHERE
  mt.mB =(
  SELECT
    MAX(mB)
  FROM
    thundersense mt2
  WHERE
    mt2.UTC >(UNIX_TIMESTAMP() -3600))
  ORDER BY
    utc
  DESC
LIMIT 1

如何修改它以便返回最大值和最大值最低和各自的时间?

你的Simon M。

2 个答案:

答案 0 :(得分:1)

一种方法使用join

SELECT mt.mB as Hr_mB_Max, mt.UTC as Hr_mB_Max_when
FROM thundersense mt JOIN
     (SELECT MAX(mB) as max_mb, MIN(mb) as min_mb
      FROM thundersense mt2
      WHERE mt2.UTC >(UNIX_TIMESTAMP() - 3600)
     ) mm
     ON mt.mB IN (mm.max_mb, mm.min_mb)
ORDER BY utc DESC;

我唯一关心的是你的limit 1。据推测,mB应该是唯一的。如果没有,那就有一点挑战。一种可能性是使用自动递增的id而不是mB

答案 1 :(得分:1)

根据我对您的问题的理解,您希望创建一个4列和1行答案,如下所示:

+-------+-----------------+----------+-----------------+
| event | time_it_occured |  event   | time_it_occured |
+-------+-----------------+----------+-----------------+
| fun   |           90000 | homework |           12000 |
+-------+-----------------+----------+-----------------+

以下是您可以根据自己的情况调整的类似情况/查询。

因此,给出一个名为'people'的表格,如下所示:

+----+------+--------+
| ID | name | salary |
+----+------+--------+
|  1 | bob  |  40000 |
|  2 | cat  |  12000 |
|  3 | dude |  50000 |
+----+------+--------+

您可以使用此查询:

SELECT * FROM 
(SELECT name, salary FROM people WHERE salary = (SELECT MAX(salary) FROM people)) t JOIN
(SELECT name, salary FROM people WHERE salary = (SELECT MIN(salary) FROM people)) a;

生成:

+------+--------+------+--------+
| name | salary | name | salary |
+------+--------+------+--------+
| bob  |  40000 | cat  |  12000 |
+------+--------+------+--------+

有些注意事项:

  1. 您可以将WHERE子句更改为您提到的那些(MAX和MIN)。
  2. 请注意上面的查询,这里我使用的是笛卡尔连接(MYSQL中的交叉连接)以获得4列。说实话,对我来说,在一行中取回数据是没有意义的,但是你说这就是你要找的东西。
  3. 以下是我将使用的内容,返回两个元组/行:

    +----------+--------+
    | name     | salary |
    +----------+--------+
    | dude     | 95000  |
    | Cat      | 12000  |
    +----------+--------+
    

    要生成这个,你可以使用:

    (SELECT name, salary FROM instructor WHERE salary = (SELECT MAX(salary) FROM instructor))
    UNION
    (SELECT name, salary FROM instructor WHERE salary = (SELECT MIN(salary) FROM instructor));
    

    另外:没有ON子句的JOIN只是一个CROSS JOIN。 How to use mysql JOIN without ON condition?