开发者

Query to find all no associated entities

开发者 https://www.devze.com 2023-02-08 21:26 出处:网络
I have two tables, USERS and USERS_ASSOCIATIONS For simplistic sake they look like this USERSUSERS_ASSOCIATION

I have two tables, USERS and USERS_ASSOCIATIONS

For simplistic sake they look like this

USERS       USERS_ASSOCIATION
-----      --------------------------
|id |      |id  |fk_id| fk_assoc_id |
-----      --------------------------
| 1 |      | 1  |  1  | 2           |
| 2 |      | 2  |  1  | 3           |
| 3 |      --------------------------
| 4 |
-----

users can be associated to each other so for this example user with ID of 1 is associated to user 2 and 3 but not to 4.

I am trying to create a query that will find all users that are not associated to a specific user. So for the example of user 1 the result of the query will be 4 , if the user were 2 then the res开发者_JAVA技巧ult of the query would be 1 , 3 , and 4 because user two has no associations.

So far have have this

SELECT * from USERS WHERE AND USERS.id <> ( SELECT * FROM USERS_ASSOCIATION as UA INNER JOIN USESR as U ON UA.fk_assoc_id = U.id AND UA.fk_id = 1);

I know this is wrong, the sub query returns a list of all of the USER_ASSOCIATIONS that are found for a particular user.


Looks like you just need a "not in" rather than the "<>"... This should return the list of users that "are not in" the subquery.

SELECT * 
from USERS 
WHERE AND USERS.id not in ( SELECT * FROM USERS_ASSOCIATION as UA INNER JOIN USESR as U ON UA.fk_assoc_id = U.id AND UA.fk_id = 1);


select *
from USERS
where id <> 1
and id not in (select fk_id from USERS_ASSOCIATION where fk_assoc_id = 1)
and id not in (select fk_assoc_id from USERS_ASSOCIATION where fk_id = 1)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号