简体   繁体   English

带有AND条件的MYSQL多对多选择

[英]MYSQL many-to-many selection with AND condition

I found a similar question in stackoverflow, but it is not quite the problem I am facing right now.我在 stackoverflow 中发现了一个类似的问题,但这并不是我现在面临的问题。 I could not find a better way of describing the required query, than the following:我找不到比以下更好的方法来描述所需的查询:

Select all the entries which have at least the property one AND property two AND ...选择至少具有属性一 AND 属性二 AND ... 的所有条目

Consider the following tables:考虑以下表格:

users用户

|  id  |  name  |
+------+--------+
|  1   |  john  |
+------+--------+
|  2   |  liu   |
+------+--------+  

sports运动的

|  id  |  user_id  |    sport   |
+------+-----------+------------+
|  1   |     1     |    swim    |
+------+-----------+------------+
|  2   |     1     |    run     |
+------+-----------+------------+
|  3   |     1     |  football  |
+------+-----------+------------+
|  4   |     1     |   volley   |
+------+-----------+------------+
|  5   |     2     |    swim    |
+------+-----------+------------+
|  6   |     2     |    run     |
+------+-----------+------------+

I would like to be able to make the following queries:我希望能够进行以下查询:

  1. Select all users who only swim (straight forward)选择所有只会游泳的用户(直接)

Returns:返回:

|  id  |  name  |
+------+--------+
|  1   |  john  |
+------+--------+
|  2   |  liu   |
+------+--------+
  1. Select all users who can swim AND run选择所有会游泳和跑步的用户

Returns:返回:

|  id  |  name  |
+------+--------+
|  1   |  john  |
+------+--------+
|  2   |  liu   |
+------+--------+
  1. Select all users who can swim AND run AND play football选择所有会游泳、跑步和踢足球的用户

Returns:返回:

|  id  |  name  |
+------+--------+
|  1   |  john  |
+------+--------+

The number of sports should be dynamic.运动的数量应该是动态的。

Thank you.谢谢你。

The number of items in the list can't really be "dynamic", at least not any more than any list of values can be.列表中的项目数量不能真正是“动态的”,至少不能超过任何值列表。

SELECT u.id, u.name
FROM users AS u
INNER JOIN sports AS s ON s.user_id = u.id
WHERE s.sport IN ('football','run','swim')
GROUP B u.id, u.name
HAVING COUNT(DISTINCT sport) = 3
;

For longer/shorter lists, you just need to adjust the 3 accordingly.对于更长/更短的列表,您只需要相应地调整3

To check for all 3 you can do要检查所有 3 个你可以做的

select u.id, u.name
from users u
join sports s on s.user_id = u.id
group by u.id, u.name
having sum(sport = 'swim') > 0
   and sum(sport = 'run') > 0
   and sum(sport = 'football') > 0

Remove the ones from the query that you don't need for the other selects.从查询中删除其他选择不需要的那些。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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