我有一个类似于下表的表格
id | mainID | subID
1 | 11 | 0
2 | 12 | 0
3 | 13 | 20
4 | 13 | 21
5 | 15 | 0
如果subID为0,我需要选择所有的“ mainID”。如果subID不为0,则选择subID而不是mainIdD
结果表
id | resultId
1 | 11
2 | 12
3 | 20
4 | 21
5 | 15
subID列的值不为null,因此在这里不能使用ifnull。可以仅使用sql查询来完成此操作吗?并且不要在php中使用write函数。我知道可以在php中完成,但我需要sql查询本身中的数据。
您可以使用一个case
表达式:
select id, (case when subid = 0 then mainid else subid end) as resultid
from t;
对于您的示例数据,greatest()
也可以使用:
select id, greatest(subid, mainid) as resultid
或者,如果您将“ 0”值存储为NULL
而不是0
,那么coalesce()
最好:
select coalesce(subid, mainid) as resultid
如果“ 0”表示没有匹配值,则NULL
很有意义。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句