选择一个匹配条件或第一个,如果没有

时间:2014-05-11 20:01:19

标签: mysql sql mariadb

我有一张包含一些数据的表格。它看起来像是:

MariaDB [lokatnik]> SELECT id_elixir, start_time FROM elixir ORDER BY start_time ASC;
+-----------+------------+
| id_elixir | start_time |
+-----------+------------+
|         3 | 00:00:00   |
|         1 | 12:30:00   |
|         2 | 13:30:00   |
+-----------+------------+
3 rows in set (0.00 sec)

现在,我需要准确选择一行匹配时间条件 - 比如 - start_time> some_time。

例如:

  • 当some_time是10:00时,我需要一行id_elixir = 1(第一行时间超过10:00),
  • 当some_time是13:00时,我需要一行id_elixir = 2(如上所述),
  • 当some_time是14:00时,我需要id_elixir = 3的行。

如何使用SQL(和MySQL / MariaDB DBMS)获取此行?

1 个答案:

答案 0 :(得分:0)

也许,这样的事情对你有用:

SELECT
  *
FROM
  elixir
WHERE
  CASE
    WHEN start_time BETWEEN CAST('10:00:00' AS TIME) AND CAST('13:00:00' AS
      TIME)
    THEN id =1
    WHEN start_time BETWEEN CAST('13:00:00' AS TIME) AND CAST('14:00:00' AS
      TIME)
    THEN id         =2
    WHEN start_time > CAST('14:00:00' AS TIME)
    THEN id         =3
    ELSE true

但你可以通过使用简单的布尔运算符来实际检查:

SELECT
  *
FROM
  elixir
WHERE
  (
    start_time BETWEEN CAST('10:00:00' AS TIME) AND CAST('13:00:00' AS TIME)
  AND id =1
  )
OR
  (
    start_time BETWEEN CAST('13:00:00' AS TIME) AND CAST('14:00:00' AS TIME)
  AND id =2
  )
OR
  (
    start_time > CAST('14:00:00' AS TIME)
  AND id       =3