6

私はこのようなテーブルを持っています:

表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フィールドの1つにnull値がある場合、行が表示されるようになりました。行を完全に非表示にするのではなく、null値がある場合は「-」として表示する必要があります。

SQLFIDDLE HERE

4

2 に答える 2

1

これを試してください - JOIN の代わりに LEFT 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 フィドル

于 2013-10-31T07:41:38.070 に答える