2014-02-15 76 views
0

我怎麼能寫出下面的SQL如何寫一個適當的IF CASE在MySQL WHERE條件

select * from blogimage where blog_id = '1' and orientation = 'h' 

但是......我想添加....

IF(and only if) orientation = 'h' is null... then use orientation = 'v' 
+0

'orientation ='h'is null'是一個扁平的語法錯誤。你的意思是像SELECT IF(orientation IS NULL,'v','h')'嗎? –

+0

不,我想得到方向='h'的位置......但在沒有方位'h'的結果的情況下....我將取向爲'v'。 – user3011784

回答

0

如果你只想要獲得1條記錄,並且偏好方向='h'

SELECT * FROM blogimage 
WHERE blog_id = '1' AND (orientation = 'h' OR orientation = 'v') 
ORDER BY orientation ASC LIMIT 1 
+0

但我想在方向'v'上設置orientation ='h'的優先順序...所以blog_id = 1同時具有h和v圖像...我只想要h。 – user3011784

+0

,如果blog_id沒有圖像'h'...那麼只有這樣我纔會使用'v' – user3011784

+0

我剛剛更新了我的答案。我認爲以簡單的方式解決您的需求。 –

0

此聲明具有有效的Case聲明。但是,如果您的意思是您需要一個if exists聲明,我認爲您需要爲這些聲明使用存儲過程。那是你想要創造的嗎?

使用此語句,您將返回一行。如果有一排h,則會將其還原。如果沒有,你將得到一個v行,除非它不存在。

select * from blogimage where blog_id = '1' and (orientation = 'h' Or orientation = 'v') Order By Case When orientation = 'h' Then 0 Else 1 End Asc Limit 1