简体   繁体   中英

How to select multiple rows of the same user that satisfies some condition in SQL?

A have the following data

id user_id visited_country
1  12      Spain 
2  12      France
3  14      England
4  14      France
5  16      Canada
6  14      Spain 

I want to select all users who have visited both Spain and France . How can I do that in MySQL?

Something like the following should suffice:

select user_Id
from t
where visited_country in ('Spain','France')
group by User_Id
having Count(distinct visited_country) = 2;

@Aman: If you are trying to exclude England then it would be

select distinct user_Id
from table
where visited_country in ('Spain','France')
and not exists
(Select distinct user_id
 From table where visited_country in ('England'))
group by User_Id
having Count(distinct visited_country)> = 2;

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