我有以下表格,需要进行查询
Clubs( club_id, name )
Facilities ( id, club_id, name )
逻辑是俱乐部可以拥有一个或多个设施,我需要一个简单的查询来基本搜索所有拥有某些设施的俱乐部
例如。所有俱乐部都有足球和网球场设施
SELECT *
FROM (`clubs`)
JOIN `club_facilities` ON `club_facilities`.`club_id` = `clubs`.`id`
WHERE `facility_id` = 1
AND `facility_id` = 3
这会返回0结果 - 但是如果将其更改为以下
SELECT *
FROM (`clubs`)
JOIN `club_facilities` ON `club_facilities`.`club_id` = `clubs`.`id`
WHERE `facility_id` = 1
OR `facility_id` = 3
我从数据库中得到两个结果(行) - 我认为我需要做一些额外的自我加入,但不完全确定如何做到这一点。任何人都可以提出一些建议。
由于
答案 0 :(得分:2)
两次加入设施表。
SELECT * FROM clubs
JOIN club_facilities f1 ON club_id = clubs.id
JOIN club_facilities f2 ON club_id = clubs.id
WHERE f1.facility_id = 1
AND f2.facility_id = 3
或使用子选择:
SELECT * FROM clubs
WHERE EXISTS(SELECT * FROM club_facilities WHERE club_id = clubs.id AND facility_id = 1)
AND EXISTS(SELECT * FROM club_facilities WHERE club_id = clubs.id AND facility_id = 3)
答案 1 :(得分:1)
SELECT clubs.id FROM clubs JOIN club_facilities ON (club_id=clubs.id)
WHERE facility_id IN (1,3)
GROUP BY clubs.id
HAVING count(DISTINCT facility_id)=2;
将为您提供符合IN (1,3)
条件的设施数量为2(即两者)的俱乐部。