SQL:如何根据另一个表中的值查询一个表中是否存在记录

时间:2015-03-25 03:06:55

标签: sql sql-server

我有两张桌子:

project_members:
[project_id,user_id]
1,1
1,2
2,1

employees:
[user_id]
1
2
3

我需要的是一个SQL语句,它将列出所有没有来自其中员工的所有user_id的project_id,以及它们缺少的后续user_id。

所以结果会是这样的:

[project_id, user_id]
1,3
2,2
2,3

因为其中的project_id 1和user_id 3不存在记录,依此类推。

感谢您解决这个问题的任何/所有帮助。

2 个答案:

答案 0 :(得分:1)

首先,您要生成project_membersemployees的所有组合。您可以使用CROSS JOIN执行此操作。然后,您可以使用NOT EXISTS来获得所需的结果。

SQL Fiddle

SELECT
    p.project_id,
    e.user_id
FROM(
    SELECT DISTINCT project_id FROM project_members
)p
CROSS JOIN employees e
WHERE
    NOT EXISTS(
        SELECT 1 FROM project_members
        WHERE
            project_id = p.project_id
            AND user_id = e.user_id
    )

在检查是否存在LEFT JOIN

时,您还可以使用project_members
SELECT
    p.project_id,
    e.user_id
FROM(
    SELECT DISTINCT project_id FROM project_members
)p
CROSS JOIN employees e
LEFT JOIN project_members pm
    ON pm.project_id = p.project_id
    AND pm.user_id = e.user_id
WHERE
    pm.project_id IS NULL

答案 1 :(得分:1)

//Filtering records which are not available in Project table.
SELECT a.ProjectId, b.ProjectId, b.UserId
FROM Project a
RIGHT JOIN 
(
/* Here, all the projects will be linked to all the users. So, All users will be assigned to all the projects. */
SELECT DISTINCT a.ProjectId, b.UserId
FROM Project a
CROSS JOIN Users b
) b ON a.ProjectId = b.ProjectId and a.UserId = b.UserId
WHERE a.ProjectId IS NULL
ORDER BY b.ProjectId

INNER QUERY
Project.Project_Id, Project.User_id, Employee.UserId
1, 1, 1
1, 1, 2
1, 1, 3
1, 2, 1
1, 2, 2
1, 2, 3
2, 1, 1
2, 1, 2
2, 1, 3

Distinct Project.Project_Id, Employee.UserId
1, 1
1, 2
1, 3
2, 1
2, 2
2, 3

Outer query, taking records which are not available in Project table.

Please let me know for any issues