我有一个包含产品的表,一个包含产品标签的表,每个产品可以有几个标签,例如
products
product_id|name|…
1 |book
2 |game
3 |desk
…
,
tags
product_id|tag
3 |used
3 |physical
有没有一种“好”的方法,只使用SQL来查询所有产品,这些产品都有给定的标签,其中标签在一个数组中,只有在编译时才知道?
我能想到的唯一方法是以编程方式在tags
上生成一个包含多个JOIN
的查询,重命名为tag1
、tag2
等,然后在WHERE
子句中使用tag1 = tags_array[1] AND tag2 = tags_array[2]
等进行过滤。
我使用的是SQLITE,如果这是相关的。
3条答案
按热度按时间0ejtzxu11#
对于给定的标记列表,可以使用关系除法。假设我们需要同时具有
'used'
和'physical'
标记的所有产品的ID如果你要参数化这个查询,你只需要:
in
子句中以编程方式生成产品列表(所需标记的数量是可变的,这会影响查询字符串)having
子句请注意,SQLite不支持开箱即用的数组。
如果你也想要产品名称,我们可以加入
products
:ercv8c1e2#
您可以使用
GROUP BY
、HAVING
和子查询的组合:3ks5zfa03#
您可以对标记数组进行过滤,以轻松计算其长度,然后可以在having子句中使用该长度。
Demo here