问题
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