如果 mySQL 中所选值为“0”,则从另一列中选择

Kur*_*ate 0 mysql sql

我有一张类似于下表的表格

id | mainID | subID
1  |   11    |   0
2  |   12    |   0 
3  |   13    |   20
4  |   13    |   21
5  |   15    |   0
Run Code Online (Sandbox Code Playgroud)

如果 subID 为 0,我需要选择所有“ mainID ”。如果 subID 不为 0,则选择 subID 而不是 mainIdD

结果表

id | resultId
1  | 11
2  | 12
3  | 20
4  | 21
5  | 15
Run Code Online (Sandbox Code Playgroud)

subID 列值不为 null,因此我不能在此处使用 ifnull。只用sql查询就能完成吗?并且不在 php 中使用 write 函数。我知道它可以在 php 中完成,但我需要来自 sql 查询本身的数据。

Gor*_*off 5

您可以使用一个case表达式:

select id, (case when subid = 0 then mainid else subid end) as resultid
from t;
Run Code Online (Sandbox Code Playgroud)

对于您的示例数据,greatest()也可以:

select id, greatest(subid, mainid) as resultid
Run Code Online (Sandbox Code Playgroud)

或者,如果您将“0”值存储为而NULL不是0,那么coalesce()最好:

select coalesce(subid, mainid) as resultid
Run Code Online (Sandbox Code Playgroud)

如果“0”表示没有匹配值,则NULL很有意义。