Using NOT IN with NOT EQUAL when querying

自作多情 提交于 2019-12-11 15:31:19

问题


I've got a table named "Positions" and I'm trying to get specific information out of. As an example:

Position ID           Person

4                     Joe
5                     Mary
4                     Mary
6                     Shawn
4                     Brad
4                     Ken
8                     Ken

Note that a Person can have more than one Position ID.

I need to pull out all the names of Persons with a Position Id equal to 4, BUT they also cannot have another Position ID other than 4 as well.

I've tried creating a list of all users who have position ID's other than 4, and then saying I don't want any users from that list. The logic being that this would remove Persons who don't have ID's of 4, as well as users who DO have ID's of 4 but ALSO have Positions ID's other than 4. Note, this is in MySQL and I'm rather new to it, but I'd imagine the SQL logic to follow through.

SELECT

Person

FROM

Positions

WHERE Person NOT IN

(
SELECT Person

FROM
Positions

WHERE
Position_ID <> 4
)

I would expect results to only show Joe and Brad

I keep getting no returns on my results at all, no matter how simple I make it.


回答1:


First, you are doing a SELECT on 'Persons'. You have two columns named Position Id and Person. Start with that

SELECT * FROM Positions WHERE person NOT IN (SELECT person WHERE position_id != 4);



回答2:


I would simply use aggregation

select person
from positions
group by person
having min(position) = max(position) and  -- all positions are the same
       min(position) = 4;


来源:https://stackoverflow.com/questions/57084658/using-not-in-with-not-equal-when-querying

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!