查询以获得大于零且不为NULL的最低值

时间:2012-03-13 13:19:55

标签: mysql

我有一个问题:

SELECT
    taskDeadline,
    subtasksDeadline,
    REPLACE(
        LEAST(
            COALESCE(t.deadline, 2147483647),
            COALESCE(sub.deadline, 2147483647)
        ), 2147483647, NULL
    ) AS Deadline
FROM
    tasks t
    LEFT OUTER JOIN subtasks sub ON sub.task_id = t.id

这会产生如下结果:

taskDeadline | subtasksDeadline | Deadline
1338501600   | 1333058400       | 1333058400
1334268000   | NULL             | 1334268000
NULL         | 1328050800       | 1328050800
NULL         | NULL             | NULL
1353798000   | 0                | 0
0            | 1353798000       | 0

我快到了。我使用2147483647作为数据类型(Mysql INT)的最大值,我仍然唯一的问题是,如果我有两个值,其中一个是0,我想得到另一个值。我花了一些时间但却无法到达那里。有人可以对此有所了解吗?

4 个答案:

答案 0 :(得分:2)

或者只是将NULLIF添加到现有的COALESCE -

SELECT
    taskDeadline,
    subtasksDeadline,
    NULLIF(
        LEAST(
            COALESCE(NULLIF(t.deadline, 0), 2147483647),
            COALESCE(NULLIF(sub.deadline, 0), 2147483647)
        ), 2147483647
    ) AS Deadline
FROM
    tasks t
    LEFT OUTER JOIN subtasks sub ON sub.task_id = t.id

答案 1 :(得分:1)

为什么不使用案例陈述?

SELECT
    taskDeadline,
    subtasksDeadline,
    CASE
        WHEN t.deadline IS NULL AND sub.deadline IS NULL THEN NULL
        WHEN t.deadline IS NULL THEN sub.deadline
        WHEN sub.deadline IS NULL THEN t.deadline
        WHEN t.deadline > sub.deadline THEN sub.deadline
        WHEN sub.deadline > t.deadline THEN t.deadline
        WHEN sub.deadline = t.deadline THEN sub.deadline -- or this could be t.deadline
     END AS Deadline
FROM
    tasks t
    LEFT OUTER JOIN subtasks sub 
        ON sub.task_id = t.id

答案 2 :(得分:0)

如果我理解正确,如果零最小,则不希望t.deadlinesub.deadline为零。所以你可以将0转换为NULL,这将被挤出COALESCE

SELECT
    taskDeadline,
    subtasksDeadline,
    REPLACE(
        LEAST(
            COALESCE(IF(t.deadline = 0, NULL, t.deadline), 2147483647),
            COALESCE(IF(sub.deadline = 0, NULL, sub.deadline), 2147483647)
        ), 2147483647, NULL
    ) AS Deadline
FROM
    tasks t
    LEFT OUTER JOIN subtasks sub ON sub.task_id = t.id

答案 3 :(得分:0)

尝试使用此查询 -

SELECT
    taskDeadline,
    subtasksDeadline,
    LEAST(
      IF(t.deadline = 0 OR t.deadline IS NULL, sub.deadline, t.deadline),
      IF(sub.deadline = 0 OR sub.deadline IS NULL, t.deadline, sub.deadline)
    ) AS Deadline
FROM
    tasks t
    LEFT OUTER JOIN subtasks sub ON sub.task_id = t.id