SQL JOIN问题丢弃结果

问题描述:

用户#1连接到扇区#1SQL JOIN问题丢弃结果

项目#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 

Exepected结果:

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 

感谢

+0

你正在使用哪个dbms? (有些非ANSI SQL ......) – jarlh

+0

我使用MySQL – user3006522

+0

添加一些示例表数据和预期结果。 (以及格式化文本) – jarlh

你并不需要表连接在一起 - 除非你关心的项目,没有部门可言。

要消除整行,您希望在之后进行过滤的聚合。这里有一个方法:

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子句检查没有匹配。

+0

Merci beaucoup :) – user3006522