2017-04-14 5 views
1

投稿からuser_id 1と2を受け取りました。私は単一テーブルによるMySQL相互条件クエリ

id | name 
4 | abc hospital 
5 | XYZ hospital 
9 | def hospital 

私が欲しい4.

user_hopitalsテーブル

id | user_id | hospital_id 
1 | 1  | 4 
2 | 2  | 4 
3 | 1  | 5 
4 | 2  | 9 

病院のテーブルのように、両方のユーザーが、病院のIDの共有を取得したい

hospital_id | hospital_name 
    4  | abc hospital 

答えて

0

基本的な考え方のようなデータ集約しており、having句:

select uh.hospital_id, uh.name 
from user_hospitals uh join 
    hospitals h 
    on uh.hopital_id = h.id 
where uh.user_id in (1, 2) 
group by uh.hospital_id, uh.name 
having count(distinct uh.user_id) = 2; 
1

あなたは例えば、SELF JOINを使用することができます:それは完璧に働いている

SELECT h.id. h.name 
FROM user_hospitals uh1 JOIN user_hospitals uh2 ON uh1.hospital_id = uh2.hospital_id 
JOIN hospitals h ON uh1.hospital_id = h.id 
WHERE uh1.user_id = 1 AND uh2.user_id = 2; 
+0

感謝を。 –

関連する問題