Mysql查询减去问题

时间:2016-03-03 23:30:22

标签: mysql sql nested

您好请考虑下表


user_id  city_id role_id 
 101      1       a
 101      2       b
 101      3       c

我想要的是

Input                    Output
city id  role_id
1,2,3                   All user_ids present in city_id 1 and 2 and 3 
1,2       c             All user_ids present in city_id 1 and 2 and not present in role_id c 
1         b,c           All user_ids present in city_id 1 and not present in role_id b,c
2         a,c           All user_ids present in city_id 2 and not present  in role_id a,c   

最简单的方法是什么?注意:表中有大量记录,因此性能也很重要。

因此,在上面的示例中,只有在我通过city_id 1,2,3

时才会返回101

我试过

select user_id,  city_id, role_id from foo_table where city_id in 
(1,2)  and role_id not in ('c') group by user_id having count(*) = 2;

select user_id,  city_id, role_id from foo_table where city_id in 
(1,2)  and user_id not in (select user_id from foo_table where role_id not in ('c')); 

结果不正确。

更新 我需要这样的东西


    select * from (select * from foo_table where city_id in (1)) s1
    inner join (select * from foo_table where city_id in (2)) s2 
    on s1.user_id = s2.user_id
    and s1.user_id not in (select distinct(user_id) from foo_table where role_id in('c'));

我还在测试它。

2 个答案:

答案 0 :(得分:0)

我觉得你可能会遇到比你下面看到的更复杂的事情,但我试图从字面上解释你的简短问题。即,对于不同的标准集,您请求user_id符合这些条件的列表。SQL Fiddle

MySQL 5.6架构设置

CREATE TABLE foo_table
    (`user_id` int, `city_id` int, `role_id` varchar(1))
;

INSERT INTO foo_table
    (`user_id`, `city_id`, `role_id`)
VALUES
    (101, 1, 'a'),
    (101, 2, 'b'),
    (101, 3, 'c'),
    (101, 4, 'd')
;

查询1

Input                    Output
city id  role_id
1,2,3                   All user_ids present in city_id 1 and 2 and 3 

select user_id 
from foo_table 
where city_id in (1,2,3) 
group by user_id
having count(distinct city_id) = 3

<强> Results

| user_id |
|---------|
|     101 |

查询2

Input                    Output
1,2       c             All user_ids present in city_id 1 and 2 and not 

select user_id 
from foo_table 
where city_id in (1,2) 
and role_id not in ('c') 
group by user_id
having count(distinct city_id) = 2

<强> Results

| user_id |
|---------|
|     101 |

查询3

Input       Output
1     b,c   All user_ids present in city_id 1 and not present in role_id b,c

select user_id 
from foo_table 
where city_id in (1) 
and role_id not in ('b','c') 
group by user_id

<强> Results

| user_id |
|---------|
|     101 |

查询4

Input       Output
2     a,c   All user_ids present in city_id 2 and not present  in role_id a,c  

select user_id 
from foo_table 
where city_id in (2) 
and role_id not in ('a','c') 
group by user_id

<强> Results

| user_id |
|---------|
|     101 |

答案 1 :(得分:0)

这就是我所需要的:

Select a.* 
From foo_table a , 
   (Select user_id 
    From foo_table 
    Where city_id in(1,2)   
          and role_id not in('c') 
    Group by user_id 
    Having count(*) = 2) b
Where a.city_id in(1,2)
       And a.city_id = b.city_id;