连接表中的记录,存在且不存在
表格文章;
+------------+-------+--------+-
| id| cat-id |aut-id |content |
+------------+-------+--------+
| 1 | 1 | 3 |eeeeeee |
| 2 | 2 | 4 |fffffff |
| 3 | 8 | 5 |ggggggg |
| 4 | 9 | 2 |jjjjjjj |
+------------+-------+--------+
表类别;
+--------------+
| id| cat-name |
+--------------+
| 1 | phy |
| 2 | che |
| 3 | bio |
+--------------+
表作者;
+--------------+
| id| aut-name |
+--------------+
| 4 | joe |
| 5 | sam |
| 6 | kim |
+--------------+
我想要这个结果
+------------+-------+--------+--------+--------+
| id| cat-id |aut-id |cat-name|aut-name|content |
+------------+-------+--------+--------+--------+
| 1 | 1 | 3 | phy |unknown |eeeeeee |
| 2 | 2 | 4 | che | joe |fffffff |
| 3 | 8 | 5 | uncat | sam |ggggggg |
| 4 | 9 | 2 | uncat | unknown|jjjjjjj |
+------------+-------+--------+--------+--------+
答案 0 :(得分:0)
只是LEFT JOIN数据,所以你不会过滤掉缺失的数据
SELECT
a.`id`,
a.`cat-id` ,
a.`aut-id` ,
COALESCE(c.`cat-name`, 'uncat') as 'cat-name',
COALESCE(a1.`aut-name`, 'unknown') as 'aut-name' ,
a.`content`
FROM `article` a
LEFT JOIN `categories` c on c.`id` = a.`cat-id`
LEFT JOIN `authors` a1 on a1.`id` = a.`aut-id`
使用COALESCE处理空值并输入您想要的结果
+------------+-------+--------+--------+--------+
| id| cat-id |aut-id |cat-name|aut-name|content |
+------------+-------+--------+--------+--------+
| 1 | 1 | 3 | phy |unknown |eeeeeee |
| 2 | 2 | 4 | che | joe |fffffff |
| 3 | 8 | 5 | uncat | sam |ggggggg |
| 4 | 9 | 2 | uncat | unknown|jjjjjjj |
+------------+-------+--------+--------+--------+