我正在接收来自post的user_id 1和2。我希望像4这样的用户分享医院ID。
user_hopitals表
x = [[a b c d e f g e b]]
res, _ = string.gsub(x, "%a b", "z")
print(res)
-- z c d e f g z
医院表
id | user_id | hospital_id
1 | 1 | 4
2 | 2 | 4
3 | 1 | 5
4 | 2 | 9
我想要像
这样的数据id | name
4 | abc hospital
5 | XYZ hospital
9 | def hospital
答案 0 :(得分: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;
答案 1 :(得分: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;