简体   繁体   中英

MySQL Joining table that must contain certain values

I have a MySQL table that contains people. Those people are assigned one or more people types. People types are stored in different MySQL table and I use joins to link the data.

What I want to do is select people within specific types.

In my example below, I want to select people who are in the people type 1234 AND 4321 . They can be in other people types too, but they must be in at least the two I've specified.

Here's my query I've tried but it returns nothing.

SELECT p.person_id
    FROM people AS p 
    INNER JOIN people_types AS pt ON pt.person_id = p.person_id AND pt.type_id IN ('1234') AND pt.type_id IN ('4321')

Is there a specific function that should allow me to do this?


EDIT

I've been recommend joining the table twice. But this seems inefficient. What if I used a LEFT JOIN instead, would that provide more flexibility?

SELECT p.person_id
    FROM people AS p 
    LEFT JOIN people_types AS pt ON pt.person_id = p.person_id
    WHERE pt.type_id IN ('1234') AND pt.type_id IN ('4321'

If you want that person should be in both types which you have specified, then you need to join PersonTypes twice. I think this should work,

SELECT p.person_id
    FROM people AS p 
    INNER JOIN people_types AS pt ON pt.person_id = p.person_id AND pt.type_id IN ('1234')
    INNER JOIN people_types AS pt1 ON pt1.person_id = p.person_id AND pt1.type_id IN ('4321')

To avoid join,

select PersonID,count(id) from PersonType
where TypeID in(1,2)
group by PersonID 
having count(id) >= 2

See Demo here

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.

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