[英]How to select particular column from table if another column includes all the set of requested values?
I have a table in MySQL named table1
which has three columns id
, user_id
(foreign_key) and destination_id
(foreign_key). 我在MySQL中有一个名为
table1
的表,该表具有三列id
, user_id
(foreign_key)和destination_id
(foreign_key)。 One user can have multiple destinations. 一个用户可以有多个目的地。
E.g Table1
id user_id destination_id
1 10 2
2 5 3
3 10 4
4 10 5
5 9 10
6 5 12
7 8 2
I get a request from the client side in PHP script; 我从客户端用PHP脚本收到请求; the request includes destination ids in an array.
该请求在数组中包含目标ID。
E.g. $request = array('destination_id' => [2,4,5]);
I just want to get all the user_id from table1 if and only if the particular user_id contains all requested destinations. 我只想从table1中获取所有user_id,并且仅当特定的user_id包含所有请求的目的地时。
I tried to achieve this using 'IN' operator. 我试图使用'IN'运算符来实现这一点。 ie
即
SELECT user_id FROM table1 WHERE destination_id IN ($requestedDestinationsInCommaSeparatedString)
It gives row including user_id 8 along with user_id 10 but I just need user_id 10. I just wanted to know the concept regarding the solution to the following problem. 它给出了包括user_id 8和user_id 10的行,但是我只需要user_id10。我只是想了解有关以下问题的解决方案的概念。 I am a beginner in SQL, any help would be very appreciable.
我是SQL的初学者,任何帮助都将不胜枚举。 Thanks.
谢谢。
You can check that a user_id refers to all requested destination by grouping and counting the destinations. 您可以通过对目的地进行分组和计数来检查user_id是否引用了所有请求的目的地。
SELECT user_id
FROM table1
WHERE
destination_id IN (2,4,5)
GROUP BY
user_id
HAVING count(*) = 3
-- count must be the number of elments in (2,4,5)
For doing so, the field combination of user_id and destination_id must be unique over all records. 为此,user_id和destination_id的字段组合在所有记录上必须唯一。
The only thing I can think of is to use multiple subselects and build the query string in PHP. 我唯一能想到的就是使用多个子选择并在PHP中构建查询字符串。
So for your specific example the SQL-Query-String generated should be 因此,对于您的特定示例,生成的SQL-Query-String应该为
SELECT user_id
FROM table1
WHERE user_id IN
(SELECT user_id FROM table1 WHERE destination_id = 2)
AND user_id IN
(SELECT user_id FROM table1 WHERE destination_id = 4)
AND user_id IN
(SELECT user_id FROM table1 WHERE destination_id = 5)
GROUP BY user_id
I think programming the function which generates the middle part for you shouldn't be too hard. 我认为对为您生成中间部分的功能进行编程应该不太困难。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.