你好,請考慮下表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'));
我還在測試它。
在輸出表,城市ID爲每個記錄將是用戶的輸入? –
是的輸出將是3個記錄以上的情況 –
這看起來很像一個家庭作業... – sgeddes