简体   繁体   中英

SQL Condition With Multiple Rows

I have a table which shows me my users' downloads reports. The table looks like this:

╔═══╦════════════╦═════════════╗
║   ║ url        ║ user        ║
╠═══╬════════════╬═════════════╣
║ 1 ║ Bla        ║ 1           ║
║ 2 ║ Bla Bla    ║ 1           ║
║ 3 ║ Bla Bla Bla║ 1           ║
║ 4 ║ Bla2       ║ 2           ║
╚═══╩════════════╩═════════════╝

If I want to select the user that downloaded the url Bla , I just do:

SELECT `user` FROM `links` WHERE `url` = 'Bla'

But I want to select the user that downloaded Bla and downloaded Bla Bla too.

How can I do that?

Thank you, and sorry for my English.

You can use a WHERE clause with a combination of GROUP BY and HAVING to get the result:

select user
from yourtable
where url in ('Bla', 'Bla Bla')
group by user
having count(distinct url) = 2;

See SQL Fiddle with Demo

You can use a self join

select u.user
from links u
join links u1 on(u.`user`=u1.user)
where u1.url ='Bla'
and u.url= 'Bla Bla'

Fiddle

The sqlfiddle

select 
  user, 
  group_concat(url) as urls 
from 
  links
where 
  url in ('Bla', 'Bla Bla') -- add your urls here
group by user
having count(distinct url) > 1;

在此处输入图片说明

For non-MYSQL

SELECT DISTINCT `user` FROM `links` WHERE `url`='Bla'
INTERSECT
SELECT DISTINCT `user` FROM `links` WHERE `url`='Bla Bla';

OR

For MYSQL

SELECT DISTINCT a.x AS Users_Bla_BlaBla
FROM 
( SELECT DISTINCT `user` AS x FROM `links` WHERE `url`='Bla' ) a 
INNER JOIN 
( SELECT DISTINCT `user` AS Y FROM `links` WHERE `url`='Bla Bla' ) b 
USING (x,y); 

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