我有这样的表:
表 1:
id | item_name | entered_by | modify_by
1 | banana | 2 | 1
2 | apple | 4 | 3
3 | orance | 1 | 1
4 | pineapple | 5 | 3
5 | grape | 6 | 1
表 2:
id | username
1 | admin
2 | jack
3 | danny
4 | dummy
5 | john
6 | peter
查询可以很好地选择 entered_by 或 modify_by 是否具有值:
SELECT t1.id, t1.item_name,
t2enteredBy.username enteredBy,
t2modifyBy.username modifyBy
FROM table1 t1
JOIN table2 t2enteredBy ON t1.entered_by = t2enteredBy.id
JOIN table2 t2modifyBy ON t1.modify_by = t2modifyBy.id
问题:如果 modifiy_by 或 entered_by 字段之一具有空值,该行现在显示出来,如果它具有空值而不是隐藏,我需要将其显示为“-”该行完全。
最佳答案
试试这个:
SELECT t1.id, t1.item_name,
COALESCE(t2enteredBy.username, '-') enteredBy,
COALESCE(t2modifyBy.username, '-') modifyBy
FROM table1 t1
LEFT JOIN table2 t2enteredBy ON t1.entered_by = t2enteredBy.id
LEFT JOIN table2 t2modifyBy ON t1.modify_by = t2modifyBy.id
fiddle here .
您需要一个left join
来返回那些具有null
值的行。然后 coalesce
将确保它们在 null
时被给定的字符串替换。
关于mysql - SQL:连接表也显示空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19700739/