Php 如何查询具有相同标记的多行,输出它们的所有标记,并按标记类别对结果进行排序?
我在多个网站、网店上看到过这种做法,但我想不出一种正确快速的方法 我有4张桌子:Php 如何查询具有相同标记的多行,输出它们的所有标记,并按标记类别对结果进行排序?,php,mysql,group-by,tags,sql-order-by,Php,Mysql,Group By,Tags,Sql Order By,我在多个网站、网店上看到过这种做法,但我想不出一种正确快速的方法 我有4张桌子: **pv_tags:** tag_id tag_category_id tag_name **pv_tag_connections:** tag_connection_id tag_connection_product_id tag_connection_tag_id **pv_tag_categories:** tag_category_id tag_category_name **pv_products:
**pv_tags:**
tag_id
tag_category_id
tag_name
**pv_tag_connections:**
tag_connection_id
tag_connection_product_id
tag_connection_tag_id
**pv_tag_categories:**
tag_category_id
tag_category_name
**pv_products:**
product_id
product_name
product_desc
编辑:
我想要一个MySQL查询:
- 输出与所有自定义(用户选择)标签匹配的所有产品(可以选择任意数量的标签)
- 包括找到的产品的所有其他标签(每个产品可以有任意数量的标签)
- 按用户选择的任何标签类别分组(将来可能有任意数量的类别)
- 按所选类别的标记名ASC或DESC在这些组内排序
group\u concat
适合列出所有其他标记,但我无法让它用于分组和排序
select * from pv_tag_connections
INNER JOIN pv_tags ON tag_connection_tag_id = pv_tag_id
where tag_connection_product_id IN
(
select DISTINCT tag_connection_product_id
from pv_tag_connections pc
inner join pv_tags c on pc.tag_connection_tag_id = c.pv_tag_id
where c.pv_tag_id in (1,46)
group by pc.tag_connection_product_id
having count(distinct c.pv_tag_id) = 2
)
及
我不确定哪种方法更快——它们似乎与我相似——我也可以在运行查询之前在PHP中动态构建它们。我喜欢避免的一件事是创建其他表
示例输出如下所示:
User searches for
'red' - tag_id:4, tag_category_id:1
'shoe' - tag_id:8, tag_category_id:2
'group by' - tag_category_id:4 (in stock or not)
'sort by' - tag_category_id:3 (which is here adult, child, men, women etc.)
预期结果应该是这样的
"Adioas" | "red" | "shoe" | "adult" | "in stock"
"Nile" | "red" | "shoe" | "child" | "in stock" | "20% discount"
"Nile" | "red" | "shoe" | "men" | "in stock" | "20% discount"
"Ribook" | "red" | "shoe" | "women" | "in stock" | "casual" | "with gift"
"Nile" | "red" | "shoe" | "adult" | "out of stock" | "20% discount"
"Adioas" | "red" | "shoe" | "men" | "out of stock"
"Ribook" | "red" | "shoe" | "women" | "out of stock" | "casual"
我开始觉得我错过了一些显而易见的解决办法
EDIT2:我正在考虑这个问题,结果中的这些列似乎对我来说已经足够了:
product_id | product_name | group_by_tag | sort_by_tag | group_concat with all used tags for the product
如果您向我们展示一个很好的表模式定义,并提供一些测试数据,您可能会在这里得到更多的操作。或者在这里创建一个mysql提琴,并在你的问题中放置一个链接。你是对的,谢谢。使用添加的SQL FIDLE更新。如果您向我们展示一个表的良好模式定义并提供一些测试数据,您可能会在这里获得更多操作。或者在这里创建一个mysql提琴,并在你的问题中放置一个链接。你是对的,谢谢。使用添加的SQL FIDLE更新。
product_id | product_name | group_by_tag | sort_by_tag | group_concat with all used tags for the product