2012-03-13 55 views
0

我有一個查詢:查詢來獲取這是大於零ANS最低值不爲空

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,我想其他的價值。我花了一些時間,但無法到達那裏。有人可以闡明這一點嗎?

回答

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 
+0

快速簡單。我喜歡這個解決方案。不知道關於NULLIF,非常感謝! – Leonard 2012-03-13 13:54:54

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 
1

爲什麼不使用case語句?

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 
+1

欲瞭解更多信息: http://dev.mysql.com/ DOC/refman/5.0/EN /控制流functions.html#operator_case – Hotchips 2012-03-13 13:38:11

+0

我一直認爲CASE WHEN將是緩慢的。這就是爲什麼我跳過這個選項。 – Leonard 2012-03-13 13:55:16

+0

取決於您的數據集的大小。它完全符合你對這個特定問題的需求,而且更具可讀性。 – afuzzyllama 2012-03-13 13:59:46

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