如何在mysql中写入正确的IF CASE where condition

时间:2014-02-15 04:25:30

标签: mysql

如何编写以下sql

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

但是......我想补充......

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

2 个答案:

答案 0 :(得分:0)

如果您只想获得一条适用于偏好方向='h'

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

答案 1 :(得分: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