2016-03-03 34 views
-3

你好,請考慮下表MySQL查詢零下問題

 

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 

請告訴我最簡單的方法來做到這一點?注意:我在表中有很多記錄,所以表現也很重要。

所以在上面的實施例101將只如果我通過city_id 1,2,3

我試圖

 
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')); 

我還在測試它。

+0

在輸出表,城市ID爲每個記錄將是用戶的輸入? –

+0

是的輸出將是3個記錄以上的情況 –

+2

這看起來很像一個家庭作業... – sgeddes

回答

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 | 
+0

感謝您的回覆..這裏的問題是查詢1將返回源ID,它們可能是1或2或3。 –

+0

如果你可能不那麼神祕(簡短),也許我們可以幫助更多。你有(你的想法)你想實現的東西,但基本上我幾乎不知道那是什麼,查詢1的確會返回1或2或3的ID,因爲這是我相信你所要求的。花一些時間來解釋你正在尋找什麼(編輯問題,不要使用評論)。 –

+0

我改變了查詢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;