I have a table containing project assignments represented by a projectid column and a user_assignment column which contains the user's unique userid. A user is assigned to a project if they have a record in the user assignment table associated with the project 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. I need to retrieve the project ids that the user is NOT assigned to.
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
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`;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.