SQL:连接表也显示空值

时间:2013-10-31 07:38:34

标签: mysql sql

我有这样的表:

表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

该查询可以正常工作,以选择enter_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字段中的一个具有空值,则该行现在显示出来,如果它具有空值而不是隐藏,我需要将其显示为“ - ”完全排。

SQLFIDDLE HERE

2 个答案:

答案 0 :(得分:6)

试试这个:

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

小提琴here

您需要left join来返回null个值的行。然后coalesce将确保它们被给定的字符串替换null

答案 1 :(得分:1)

试试这个 - 使用LEFT JOIN而不是JOIN

SELECT t1.id, t1.item_name,ifnull(t2enteredBy.username,'-') enteredBy,
  ifnull(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

SQL Fiddle Here