SQLite if statement in WHERE clause

一笑奈何 提交于 2019-12-24 01:21:35

问题


I know I can use CASE statement in an SQLite query but I don't know how to built it in a WHERE clause.

Actually I have this in a long WHERE clause (this is just the part concerned by the question):

AND (%d >= (wines.year + wines.maturity)) AND (%d < (wines.year + wines.apogee))

In fact I want just that :

AND (%d >= (wines.year + wines.maturity))

=> if wines.apogee IS NULL

or also:

AND (%d >= (wines.year + wines.maturity)) AND (%d < (wines.year + wines.apogee))

=> if wines.apogee IS NOT NULL

How to use the CASE statement in this case to test if wines.apogee IS NOT NULL and add the second part of the request in this case ?

Thanks !


回答1:


CASE can compute any value, even a boolean value as returned by a comparison. In SQLite, 1 is the same as "true":

...
AND %d >= (wines.year + wines.maturity)
AND CASE WHEN wines.apogee IS NOT NULL
         THEN %d < (wines.year + wines.apogee)
         ELSE 1
    END
...

The same can be done with the ifnull() function:

...
AND %d >= (wines.year + wines.maturity)
AND ifnull(%d < (wines.year + wines.apogee), 1)
...


来源:https://stackoverflow.com/questions/37355450/sqlite-if-statement-in-where-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!