SQL JOIN问题丢弃结果

时间:2016-11-22 13:15:17

标签: mysql sql join left-join

用户#1链接到扇区#1

项目#1链接到扇区#1和扇区#2
项目#2链接到扇区#2和扇区#3

我想检索项目 - 与他们的行业 - 项目不与用户#1共享任何行业

我试过了:

SELECT
    p.id,
    GROUP_CONCAT(DISTINCT s.id SEPARATOR "#") s_ids

FROM
    projects p

LEFT JOIN
    projects_x_sectors ps ON ps.id_project = p.id
LEFT JOIN
    sectors s ON s.id = ps.id_sector

WHERE
    s.id NOT IN (
        SELECT id_sector FROM users_x_sectors WHERE id_user = 1
    )

GROUP BY
    p.id

预期结果:

fetched projects = [
    {
        id: 2,
        s_ids: 2#3
    }
]

实际结果:

fetched projects = [
    {
        id: 1,
        s_ids: 2
    },
    {
        id: 2,
        s_ids: 2#3
    }
]

MySQL表:

用户

id
1

项目

id
1
2

扇区

id
1
2
3

users_x_sectors

id    id_user    id_sector
1     1          1

projects_x_sectors

id    id_project    id_sector
1     1             1
2     1             2
3     2             2
4     2             3

由于

1 个答案:

答案 0 :(得分:1)

您不需要一起加入表格 - 除非您关心的是没有任何行业的项目。

要消除整行,您希望在聚合后进行过滤。这是一种方法:

SELECT ps.id_project,
       GROUP_CONCAT(DISTINCT s.id SEPARATOR "#") s_ids
FROM projects_x_sectors ps LEFT JOIN
     users_x_sectors us
     ON ps.id_sector = us.id_sector AND us.id_user = 1
GROUP BY ps.id_project
HAVING COUNT(us.id_sector) = 0;

HAVING子句检查没有匹配。