如果数据存在于另一个表中则返回数据,否则返回默认值

时间:2017-06-26 09:56:47

标签: mysql sql

测试数据:

TableA (ID_B, uniqueID, status)

TableB (ID_B, ID_C, info)

表A:

ID_B   uniqueID   status
124    12345678   registered

表B

ID_B   ID_C   info
123    111    ilo
124    111    vey
125    111    ou
126    112    sup

如果(ID_B, ID_C, info, status)中没有指定的'Default',我想返回uniqueID状态为默认状态,例如TableA

我试过了

SELECT * FROM tableB AS tB INNER JOIN(
SELECT ID_B, COALESCE(MAX(tA.status), 'default') as status
FROM tableA AS tA
WHERE  tA.uniqueID = '12345678'
) AS tC WHERE ID_C = 111

但是,我收到所有默认状态(当tableA中不存在uniqueID时)或所有非默认状态。

以下是我想要的输出示例

ID_B  ID_C  info  status
123   111   ilo   default
124   111   vey   registered
125   111   ou    default

1 个答案:

答案 0 :(得分:0)

`
SELECT b.ID_B, 
        b.ID_C, 
        b.info, 
        COALESCE(a.status, 'Default') AS status
 FROM tabelB AS b
 LEFT JOIN tabelA AS a ON a.ID_B = b.ID_B
 WHERE b.ID_C = 123;

`