选择具有多个标签的行...有更好的方法吗?
我正在尝试建立一个标签系统来从数据库中选择产品。我读过,实现这一点的最佳方法是通过多对多关系,因为当有大量记录时,使用 LIKE '%tag%' 会变得很慢。我还读过 this 问题,在多个标签上匹配您必须为每个标签进行联接正在请求标签。
我有 3 个表:shop_products、shop_categories 和 shop_products_categories。例如,我需要能够找到同时具有“鲜花”和“浪漫”标签的产品。
SELECT p.sku, p.name, p.path FROM shop_products p
LEFT JOIN shop_products_categories pc1 ON p.sku = pc1.product_sku
LEFT JOIN shop_categories c1 ON pc1.category_id = c1.id
LEFT JOIN shop_products_categories pc2 ON p.sku = pc2.product_sku
LEFT JOIN shop_categories c2 ON pc2.category_id = c2.id
WHERE c1.path = 'flowers' AND c2.path = 'romance'
这是我当前正在构建的演示查询,用于在为其编写相关 PHP 代码之前检查它是否有效。但这真的是最好的方法吗?我发现很难相信没有比为每个搜索标签进行联接更好的方法了。 感谢您的任何建议。 :)
I am attempting to do a tag system for selecting products from a database. I have read that the best way to achieve this is via a many-to-many relationship as using LIKE '%tag%' is going to get slow when there are a lot of records. I have also read this question where to match on multiple tags you have to do a join for each tag being requested.
I have 3 tables: shop_products, shop_categories and shop_products_categories. And I need to, for example, be able to find products that have both the tag "flowers" and "romance".
SELECT p.sku, p.name, p.path FROM shop_products p
LEFT JOIN shop_products_categories pc1 ON p.sku = pc1.product_sku
LEFT JOIN shop_categories c1 ON pc1.category_id = c1.id
LEFT JOIN shop_products_categories pc2 ON p.sku = pc2.product_sku
LEFT JOIN shop_categories c2 ON pc2.category_id = c2.id
WHERE c1.path = 'flowers' AND c2.path = 'romance'
This is the demo query I'm currently building to check it works before coding the relevant PHP for it and it works. But is this really the best way to do this? I find it hard to believe there isn't a better way to do this than to do a join for each tag searched.
Thanks for any advice. :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
无需进行多次连接。如果需要匹配所有标签,可以使用带有子查询的
IN
子句,如下所示:请注意,您需要将数字 2 调整为要匹配的唯一标签的数量。请注意,这是用户输入的数据,并且他们输入相同的标签两次。
No need to do multiple joins. If you need to match all tags, you can use an
IN
clause with a subquery like this:Note that you will need to adjust the number 2 to be the number of unique tags you are matching on. Beware in case this is user-entered data and they enter the same tag twice.
确保您有这些索引:
Make sure you have these indexes: