【发布时间】:2016-01-25 01:38:31
【问题描述】:
假设我有 2 张桌子:
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?
Answer:由于两个表中都存在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
【问题讨论】:
-
左连接然后合并?
-
样本数据和期望的结果将有助于传达您想要做的事情。
-
table1_id 的 NULL 值是什么意思?左连接,table1_id 永远不会为 NULL。你是选择星,table2 只能有可能的空值