MySQL多对多查询问题

Mar*_*jan 11 mysql sql many-to-many

这是我的问题.我有一个名为'user_has_personalities'的多对多表.在我的应用程序中,用户可以拥有许多个性,个性可以属于许多用户.

该表有两个整数列,user_id和personality_id.

我需要做的是让所有用户至少拥有我提供给查询的所有个性(一组可变大小的个性化用户).

举个例子,我想让所有具有ids 4,5,7个性的用户,但也可以拥有其他一些个性.但我需要查询来处理可变数量的通缉个性ID,例如4,5,7,9,10.

有任何想法吗?

Rol*_*man 6

此查询完成工作:

select  user_id
from    user_has_personalities
where   personality_id in (<list-of-personality-ids>)
group by user_id
having count(*) = <numer-of-items-in-IN-list>
Run Code Online (Sandbox Code Playgroud)

您需要提供以逗号分隔的个性ID列表,<list-of-personality-ids>并且还需要提供优先级中的项目数.坚持你的榜样,你会得到:

select  user_id
from    user_has_personalities
where   personality_id in (4,5,7)
group by user_id
having count(*) = 3
Run Code Online (Sandbox Code Playgroud)

这可确保您只获得具有所有这些个性的用户.