具有多行的SQL条件

时间:2014-01-02 19:27:40

标签: mysql sql select

我有一张表格,向我显示用户的下载报告。 该表如下所示:

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

如果我想选择下载网址Bla的用户,我只需:

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

但我想选择下载Bla 已下载Bla Bla的用户。

我该怎么做?

谢谢你,对不起我的英语。

4 个答案:

答案 0 :(得分:5)

您可以将WHERE子句与GROUP BYHAVING结合使用,以获得结果:

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

请参阅SQL Fiddle with Demo

答案 1 :(得分:1)

您可以使用自我加入

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

Fiddle

答案 2 :(得分:0)

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;

enter image description here

答案 3 :(得分:-1)

<强> For non-MYSQL

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

OR

对于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);