简体   繁体   English

SQL SELECT Q-检索记录

[英]SQL SELECT Q - Retrieving Records

I have a table containing project assignments represented by a projectid column and a user_assignment column which contains the user's unique userid. 我有一个表,其中包含由projectid列和user_assignment列表示的项目分配,其中user_assignment列包含用户的唯一userid。 A user is assigned to a project if they have a record in the user assignment table associated with the project id. 如果用户在用户分配表中有与项目ID关联的记录,则将用户分配给项目。 I want retrieve all the projects that a specific user is NOT assigned to without getting duplicate records since there are many users assigned to projects. 我想检索没有分配给特定用户的所有项目,而不会得到重复的记录,因为有许多用户分配给项目。

While these examples will retrieve only one record per project, it returns projects that user 'abc123' is and is NOT assigned to. 虽然这些示例每个项目仅检索一条记录,但它返回用户“ abc123”已分配且未分配给用户的项目。 I need to retrieve the project ids that the user is NOT assigned to. 我需要检索未分配用户的项目ID。

SELECT DISTINCT `propid` 
FROM `user_assignments` 
WHERE `userid` <> 'abc123' 
ORDER BY `propid` ASC

SELECT DISTINCT `propid` 
FROM `user_assignments` 
WHERE (`userid` <> 'abc123') 
ORDER BY `propid` ASC

I am sure there is a very simple solution but I am not seeing it. 我敢肯定有一个非常简单的解决方案,但我没有看到。

I think what you need is the following query. 我认为您需要的是以下查询。

SELECT DISTINCT `propid` 
FROM `user_assignments` 
WHERE `propid` NOT IN (SELECT `propid` 
                     FROM `user_assignments` 
                     WHERE `userid` = 'abc123')
ORDER BY `propid`

The query gets all projects that a particular user was associated with, and then gets the ones that he was not associated with. 该查询将获取与特定用户相关联的所有项目,然后获取与该用户不相关联的项目。

EDIT: You could also try something like the following 编辑:您也可以尝试以下方法

SELECT DISTINCT o.`propid` 
FROM `user_assignments` as o
WHERE NOT EXISTS (SELECT 1 FROM `user_assignments` as i
                  WHERE `userid` = 'abc123'
                     AND i.`propid` = o.`propid`)

Or you could use JOINs to achieve this 或者您可以使用JOIN来实现这一目标

SELECT DISTINCT o.`propid` 
FROM `user_assignments` as o
    LEFT JOIN `user_assignments` as i 
        ON i.`propid` = o.`propid` AND i.`userid` = 'abc123'
WHERE i.`propid` IS NULL

The following query will probably do the trick for you. 以下查询可能会为您解决问题。

SELECT DISTINCT `propid` 
FROM `user_assignments` ua1
WHERE NOT EXISTS
(SELECT 1
FROM `user_assignments` ua2
WHERE ua1.propid = ua2.propid
AND   ua1.`userid` = 'abc123')
ORDER BY `propid`;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM