2013-10-02 83 views
0

我在IF()條件下執行SUB SELECT時遇到問題。MySQL IF()Sub Select

我試圖讓它選擇MIN保存的時間,如果類型不等於某個值,從計算中排除該值。

這裏是我當前的SQL查詢,除了作品爲IF():

SELECT 
t.episode, 
t.anime_id, 
MAX(t.type) as type, 
MIN(t.HD) as HD, 
MAX(t.thumbnail) as thumbnail, 
IF((MAX(t.type)!="raw"),(SELECT MIN(e.saved) FROM anime_episodes e WHERE e.type=MAX(t.type) AND t.episode=e.episode AND t.anime_id=e.anime_id GROUP BY e.anime_id, e.episode), (MIN(t.saved))) as time, 
// UP HERE^
MAX(t.filler) as filler, 
m.anime_name, 
m.furl, 
m.video_thumb 
FROM anime_episodes t 
LEFT JOIN anime_list m ON 
(t.anime_id=m.anime_id) 
WHERE t.approved=1 AND t.locked=0 AND m.status=0 AND t.episode>=m.latest_ep 
GROUP BY t.anime_id, t.episode 
ORDER BY time DESC LIMIT 0,24 

有什麼用我的語法怎麼回事?這看起來好像沒什麼問題,但錯誤的是:

SQL error: 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 'WHERE type!="raw")) as time, MAX(t.filler) as filler,m.anime_name, m.furl, m.vid' at line 1 

編輯:正確的答案,但我不得不增加一些分組,因爲它是返回不止一個結果。謝謝!

+0

無關你的錯誤,但你的WHERE子句檢查m.status的價值爲0,因爲這可能只有在anime_list上有一行發現LEFT OUTER JOIN無用時才爲真。 INNER JOIN會給你完全相同的結果,但是如果你只想匹配狀態爲0的記錄,那麼繼續使用LEFT OUTER JOIN,但更多的檢查m.status到JOIN的ON子句中(對於AND t .episode> = m.latest_ep) – Kickstart

回答

1

你已經忘了加上from table聲明

試試這個::

SELECT 
t.episode, 
t.anime_id, 
MAX(t.type) as type, 
MIN(t.HD) as HD, 
MAX(t.thumbnail) as thumbnail, 
IF((type="raw"),(MIN(t.saved)), (SELECT MIN(saved) from anime_episodes WHERE type!="raw")) as time, 
// UP HERE^
MAX(t.filler) as filler, 
m.anime_name, 
m.furl, 
m.video_thumb 
FROM anime_episodes t 
LEFT JOIN anime_list m ON 
(t.anime_id=m.anime_id) 
WHERE t.approved=1 AND t.locked=0 AND m.status=0 AND t.episode>=m.latest_ep 
GROUP BY t.anime_id, t.episode 
ORDER BY time DESC LIMIT 0,24 
+0

我認爲該表是anime_episodes,考慮到他也選擇type = raw的IF語句的開始。即使他沒有別名t.type ... – Hituptony

+0

謝謝!但事實證明,我必須爲了其他原因做一些補充。 –