Maybe my question will be silly, but i'm new to Mysql
I have a table with user_id and some interest.
+------+------+
|userID|Inter |
+------+------+
|1 |sport |
+------+------+
|2 |it |
+------+------+
|3 |game |
+------+------+
|1 |it |
+------+------+
|1 |game |
+------+------+
|3 |it |
+------+------+
|3 |sport |
+------+------+
Amount of interests can be huge(let say 20 or whatever)
Now i need to find all userId's that have interests it, game, sport
;
Of course simple AND wont work as because of different rows.
So my question will be how to do it, so the output will be
+------+
|userID|
+------+
|1 |
+------+
|3 |
+------+
Thank you.
asked Dec 21, 2017 at 19:45
1 Answer 1
You can get it by using GROUP BY and COUNT(*)
create table users (user_id int, interest varchar(20));
insert into users values(1, 'sport'); insert into users values(2, 'it'); insert into users values(3, 'game'); insert into users values(1, 'it'); insert into users values(1, 'game'); insert into users values(3, 'it'); insert into users values(3, 'sport');
SELECT user_id FROM users WHERE interest IN ('game', 'it', 'sport') GROUP BY user_id HAVING count(*) = 3;
| user_id | | ------: | | 1 | | 3 |
dbfiddle here
answered Dec 21, 2017 at 20:27
-
Omg.. So easy and whats important without joins. Thank you very much.Mykola Borysyuk– Mykola Borysyuk2017年12月21日 21:58:52 +00:00Commented Dec 21, 2017 at 21:58
-
-
Btw..One more small question..This query still be effective on huge datasets like 10 millions records and so on? Thank youMykola Borysyuk– Mykola Borysyuk2017年12月21日 22:06:27 +00:00Commented Dec 21, 2017 at 22:06
-
@MykolaBorysyuk I think so, but have one index on interest?McNets– McNets2017年12月21日 22:07:17 +00:00Commented Dec 21, 2017 at 22:07
-
"whats important without joins": There are several solution for this kind of problems. Many of them use joins - and are often faster than the GROUP BY - HAVING method ;)ypercubeᵀᴹ– ypercubeᵀᴹ2017年12月21日 23:04:51 +00:00Commented Dec 21, 2017 at 23:04
lang-sql