2015-08-31 178 views
0

我想在選擇查詢中的CASE WHERE裏面放一些if語句來控制順序。這是一個簡化版本,仍然給我一個語法錯誤。MySQL如果在SWITCH CASE語句裏面

SELECT stt_stid, st_stid, st_prid, st_first, st_last, YEAR(st_graduation) 
    FROM sttlink 
    INNER JOIN student ON stt_stid = st_stid 
    WHERE stt_prid = 3920103 
    GROUP BY stt_stid 
    ORDER BY 
    CASE 
     WHEN (MONTH(now())>='9') 
     THEN  
      if(YEAR(st_graduation) = YEAR(now()), 0, 1), 
      st_graduation 
     WHEN (MONTH(now())<'9') 
     THEN 
      if(YEAR(st_graduation) >= YEAR(now()), 1, 0), 
      st_graduation 
     END; 

和錯誤消息(Navicat的)是:

[Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' 
     st_graduation 
    WHEN (MONTH(now())<'9') 
    THEN 
    ' at line 13 

這裏有更多的東西(感謝到目前爲止好看!)。這是我的原始工作版本。問題是我需要有兩個不同的條款順序 - 一個是當月份是9月 - 12月,另一個是1月 - 8月。

ORDER BY if(YEAR(st_graduation)>=YEAR(now()), 0, 1), 
     if(YEAR(st_graduation)>=YEAR(now()), 10000, datediff(now(),st_graduation)), 
     st_graduation 

上面的工作很好,如果是1月 - 8月但我需要一個稍微不同的月份9月12月。

拉胡爾的答案非常接近。現在我倒在聲明裏面第二種情況:

ORDER BY 
CASE 
    WHEN (MONTH(now()) >= '9') 
    THEN  
     CASE WHEN YEAR(st_graduation) = YEAR(now()) THEN 0 ELSE 1 END, 
     CASE WHEN YEAR(st_graduation) = YEAR(now()) THEN 10000 ELSE (datediff(now(),st_graduation)) END 
    WHEN (MONTH(now()) < '9') 
    THEN 
     CASE WHEN YEAR(st_graduation) >= YEAR(now()) THEN 1 ELSE 0 END, 
     CASE WHEN YEAR(st_graduation) = YEAR(now()) THEN 10000 ELSE (datediff(now(),st_graduation)) END 
    END, st_graduation; 

我應該創建一個單獨的第二屆「主」的情況下/時 - 當相同條款,但只用第二個case語句?

+0

'語法錯誤「? –

+0

發佈一些數據樣本和預期結果。你想要達到什麼目標? – Alex

回答

1

我想你的意思做象下面這樣的情況下,使用一個Nested CASE表達

ORDER BY 
    CASE 
     WHEN MONTH(now()) >= '9' THEN  
      CASE WHEN YEAR(st_graduation) = YEAR(now()) THEN 0 ELSE 1 END 

因此,ORDER BY條款應該像

ORDER BY 
    CASE 
     WHEN (MONTH(now()) >= '9') 
     THEN  
      CASE WHEN YEAR(st_graduation) = YEAR(now()) THEN 0 ELSE 1 END   
     WHEN (MONTH(now()) < '9') 
     THEN 
      CASE WHEN YEAR(st_graduation) >= YEAR(now()) THEN 1 ELSE 0 END 
     END, st_graduation; 
+0

這非常接近!謝謝!我可以在每個主THEN內添加第二個CASE嗎?請參閱修改後的原始問題 – Steve

+0

@Steve,是的,您可以。試試看看。 – Rahul

+0

感謝Rahul和AlexGreg的指導。只需要調整它們以按照我想要的順序得到我的結果,但絕對是在這裏的障礙。 – Steve

1

怎麼樣

SELECT stt_stid, st_stid, st_prid, st_first, st_last, YEAR(st_graduation) 
    FROM sttlink 
    INNER JOIN student ON stt_stid = st_stid 
    WHERE stt_prid = 3920103 
    GROUP BY stt_stid 
    ORDER BY 
    CASE 
     WHEN (MONTH(now())>='9' and YEAR(st_graduation) = YEAR(now())) 
     THEN 
      st_graduation 
     WHEN (MONTH(now())<'9' and YEAR(st_graduation) >= YEAR(now())) 
     THEN 
      st_graduation 
     END;