使用MySQL SELECT时,您可以根据其他字段更改返回字段的值吗?
例如,如果我有这个选择:
SELECT city,state,country FROM table
Run Code Online (Sandbox Code Playgroud)
现在,如果city为空且状态为空,我希望country的值也返回空(无论country是否实际有值).
示例表:
id | city | state | country
-----------------------------
1 | Here | There | MyCountry
2 | | | YourCountry
Run Code Online (Sandbox Code Playgroud)
所以使用上面的表格,我希望id = 1的结果返回Here,There,MyCountry但是id = 2的结果应该是空的,空的,空的
谢谢
编辑:澄清一下,WHERE子句不起作用,因为我需要返回行,即使城市和州是空的.一个更好的例子可能是SELECT id,city,state,country FROM my_table
更新(更正印刷错误):
SELECT city,state,
CASE
WHEN (city IS NULL OR city='') AND (state IS NULL or state='') THEN ''
ELSE country
END as country_1
FROM `table`
Run Code Online (Sandbox Code Playgroud)
您也可以使用IF而不是CASE:
IF ((city IS NULL OR city='') AND (state IS NULL or state=''),'',country) as country_1