基于中间表的类似过滤结果

时间:2018-02-16 19:48:06

标签: php mysql sql select join

我正在尝试根据分配给每个主题的类别过滤分配给主题的类别。我有三个表,一个主题表(id,name),一个类别表(id,name),以及以一对多关系(id,topic_id,category_id)桥接两个表的表。

例如,我在热门主题公园(太空山,雷山,小世界,鬼屋,恐怖之塔,试车道等)中有一系列游乐设施和表演,列表类别(神奇王国,未婚,动物王国,惊险游乐设施,表演,家庭游乐设施,乘船游览等),以及连接它们的中间表((1,1,3),(1,1,5),(1,2) ,5)等。)。

SQLFiddle Example

我已经为单个类别的输入构建了基本查询,但我无法弄清楚如何使用多个类别进行过滤。例如,如果我查询类别'magic-kingdom'和'夜间节目',那将过滤掉诸如'epcot'和'thrill-rides'等类别。

我的查询如下:

SELECT DISTINCT scat.name FROM category AS cat 
JOIN bridge ON cat.id = bridge.cat_id 
JOIN topic ON bridge.top_id = topic.id 
JOIN bridge AS sbridge ON topic.id = sbridge.top_id 
JOIN category AS scat ON sbridge.cat_id = scat.id 
WHERE cat.slug = 'hollywood-studios' 
ORDER BY scat.name ASC

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

据我了解,您需要的类别与所有过滤类别相匹配的主题相匹配 您只需填写匹配类别列表,并对其计数进行硬编码。现在它是2

SELECT DISTINCT
  cat.name
FROM bridge b
JOIN category cat
  ON b.cat_id = cat.id
WHERE b.top_id IN (
  SELECT
    b.top_id
  FROM bridge b
  JOIN category c
    ON c.id = b.cat_id
  WHERE c.slug IN ('magic-kingdom', 'nighttime-shows')
  GROUP BY b.top_id
  HAVING count(b.cat_id) = 2
)

答案 1 :(得分:0)

在where子句中使用OR来过滤多个类别的记录,例如

SELECT DISTINCT scat.name FROM category AS cat 
JOIN bridge ON cat.id = bridge.cat_id 
JOIN topic ON bridge.top_id = topic.id 
JOIN bridge AS sbridge ON topic.id = sbridge.top_id 
JOIN category AS scat ON sbridge.cat_id = scat.id 
WHERE cat.slug = 'hollywood-studios' OR cat.slug = 'fireworks-shows'  
ORDER BY scat.name ASC