在 MySQL 中创建一个具有空值的视图



我正在尝试通过连接 2 个表在 MySQL 中创建视图,如下所示:

用户表:

+----+------+  
| id | name |
+----+------+
| 1  | Joy  |
+----+------+
| 2  | Roy  |
+----+------+
| 3  | Tony |
+----+------+  

技能表:

+---------+---------+------------+
| auto_id | user_id | skill      |
+---------+---------+------------+
| 1       | 1       | PHP        |
+---------+---------+------------+
| 2       | 1       | CSS        |
+---------+---------+------------+
| 3       | 2       | Ruby       |
+---------+---------+------------+
| 4       | 2       | Javascript |
+---------+---------+------------+  

此处的"技能"表中user_id"用户"表中id外键

用于创建视图的查询:

CREATE OR REPLACE VIEW user_view AS SELECT u.id, u.name,  GROUP_CONCAT(s.skill) as 
skills FROM users u, skills s WHERE u.id = s.user_id GROUP BY u.id  

现在的问题是创建的视图只有 2 行,我知道这是因为技能表中没有 user_id 3 的值。现在我想要的是将所有 3 行都以 Tony 的技能作为 Null 值,如下所示:

+---------+------+-----------------+
| user_id | name | skills          |
+---------+------+-----------------+
| 1       | Joy  | PHP,CSS         |
+---------+------+-----------------+
| 2       | Roy  | Ruby,Javascript |
+---------+------+-----------------+
| 3       | Tony | Null or empty   |
+---------+------+-----------------+

您正在寻找Left join

CREATE OR REPLACE VIEW user_view AS
    SELECT 
        u.id,
        u.name,
        GROUP_CONCAT(s.skill) AS skills
    FROM
        users u
            LEFT JOIN
        skills s ON u.id = s.user_id
    GROUP BY u.id

相关内容

  • 没有找到相关文章

最新更新