MySQL JOIN - 不要NULL值

时间:2016-01-25 01:38:32

标签: mysql join left-join

假设我有两张桌子:

 table1
   table1_id
   table1_name

 table2
   table2_id
   table2_name
   table2_description
   table1_id

我这样加入:

 SELECT * FROM table1 LEFT JOIN table2 ON table1.table1_id = table2.table1_id

如果table2中没有匹配项,我如何让table1_id返回其默认值而不是NULL?

答案:由于table1_id存在于两个表中,我需要使用别名。

 SELECT *, table1.table1_id AS tid, table2.table1_id AS t2id FROM table1 LEFT JOIN table2 ON table1.table1_id = table2.table1_id

2 个答案:

答案 0 :(得分:0)

如果我理解正确,你会引入默认行,然后使用select中的逻辑:

SELECT t1.*,
       COALESCE(t2.table2_name, t2def.table2_name) as table2_name,
       . . .
FROM table1 t1 LEFT JOIN
     table2 t2
     ON t1.table1_id = t2.table1_id LEFT JOIN
     table2 t2def
     ON t2def.table1_id = $defaultid;

答案 1 :(得分:-1)

SELECT table1.*
  table2.table2_id,
  table2.table2_name,
  table2.table2_description,
  ifnull(table2.table1_id, table1.table1_id) t2id
FROM table1 LEFT JOIN table2 
ON table1.table1_id = table2.table1_id

同样,没有必要检查table2.table1_id是否为null,因为它是连接列...始终为NULL或与table1.table1_id完全相同