SQL请求LEFT JOIN

时间:2012-09-11 16:08:07

标签: mysql sql request left-join

假设我有这些表格: 我的sql请求应该得到什么结果?

table user_group:

group_id          |   user_id       |   is_active
1                          2               1
1                          3               1
2                          2               1
4                          2               1

表组:

id |     name
1       group1
2       group2
3       group3
4       group4
5       group5
6       group5

预期结果

group_id       |      name      | user_id    |   is_active
 1                   group1         2               1
 2                   group2         2               1
 3                   group3         2               0
 4                   group4         2               1
 5                   group5         2               0
 6                   group6         2               0

我试过

SELECT g.id, g.name, ug.user_id, ug.is_active
FROM group g
LEFT OUTER JOIN user_group uc ON ug.group_id = g.id
WHERE ug.user_id =2

但我只有用户2为IN的组(所以group1,group2和group4)

3 个答案:

答案 0 :(得分:3)

试试这个:

SELECT  id ,
        name ,
        COALESCE(user_ID, 2) user_id ,
        COALESCE(is_active, 0) is_active
FROM    tableGroup
        LEFT JOIN user_group ON id = group_id
                                AND user_Id = 2

你可以摆弄这个here

答案 1 :(得分:1)

SELECT g.id, g.name, ug.user_id, ug.is_active 
FROM group g 
LEFT OUTER JOIN user_group uc ON ug.group_id = g.id AND ug.user_id =2 

如果在where子句中有条件,则将左连接转为内连接。

答案 2 :(得分:0)

SELECT table_group.*, user_group.user_id, IFNULL(user_group.is_active, 0)
FROM table_group
LEFT JOIN user_group ON table_group.id = user_group.group_id