您需要为每个类别 id 参数使用 find_in_set() 以查找集合中的值,如果您可以更改架构,然后通过另一个联结表来保存从该表到类别的关系,对其进行规范化表
select * from
product
where
find_in_set('142',catID ) > 0
对于像find_in_set('161,168,234,678',preferred_location ) > 0 这样的多个值,不可能这样做,您必须为每个位置ID 执行类似
select * from
product
where
find_in_set('142',catID ) > 0
and find_in_set('156',catID ) > 0
and find_in_set('146',catID ) > 0
and find_in_set('143',catID ) > 0 ... for more
Database normalization
find_in_set
示例架构
表格
- 产品(id、其他列)
- 类别(id、其他列)
- Product_categories (id,product_id,category_id)
Product_categories 是一个联结表,每个产品将保存 product_id 和一个 category_id,因此每个产品一次都与单个类别和单个产品有关系
例如
产品
id name
1 product 1
2 product 2
类别
id name
142 category 1
156 category 2
146 category 3
143 category 4
产品类别
id product_id category_id
1 1 142
2 1 156
3 1 146
4 1 143
现在您可以使用 in() 加入这些表并进行如下查询,并且 count 应该等于作为参数提供的类别 ID 的数量
select p.* from
Products p
join Product_categories pc on (p.id = pc.product_id)
where pc.category_id in(142,156,146,143)
group by p.id
having count(distinct pc.category_id) = 4
或者,如果您不能将提供的类别 ID 计为参数,您可以通过以下查询来完成此操作
select p.* from
Products p
join Product_categories pc on (p.id = pc.product_id)
where pc.category_id in(142,156,146,143)
group by p.id
having count(distinct pc.category_id) =
ROUND (
(
LENGTH('142,156,146,143')
- LENGTH( REPLACE ( '142,156,146,143', ",", "") )
) / LENGTH(",")
) + 1