2

我正在尝试使用类别表中的单个查询获取所有类别和子类别以及产品,该类别表具有子类别的 parent_id 和产品表。但我没有得到确切的结果。我不确定我在哪里做错了。

我的查询使用 5 个表,它们是:

  1. products - 此表有一个products_id字段和其他详细信息
  2. products_description - 此表包含products_nameproducts_id字段
  3. products_to_categories - 此表包含链接到categories_id字段的 products_id
  4. 类别- 此表包含categories_id及其其他字段和parent_id字段
  5. categories_description - 此表包含categories_idcategories_name字段。

这是我的查询:

SELECT  p.products_id, pd.products_name, cd.categories_id AS main_category_id, cd.categories_name ,c.categories_id AS subcategory
 FROM products p
 INNER JOIN products_description pd ON pd.products_id=p.products_id 
 INNER JOIN products_to_categories p2c ON p2c.products_id=p.products_id 
 INNER JOIN categories c ON p2c.categories_id=c.categories_id 
 INNER JOIN categories_description cd ON cd.categories_id=c.categories_id 
 GROUP BY cd.categories_id
4

1 回答 1

0

我认为你做错的是你写了 cd.categories_id=c.categories_id 的最后一个内部连接子句条件。

你应该把它改成这个 cd.categories_id=c.parent_id

所以你的最终查询将是:

SELECT  p.products_id, pd.products_name, cd.categories_id AS main_category_id, cd.categories_name ,c.categories_id AS subcategory
 FROM products p
 INNER JOIN products_description pd ON pd.products_id=p.products_id 
 INNER JOIN products_to_categories p2c ON p2c.products_id=p.products_id 
 INNER JOIN categories c ON p2c.categories_id=c.categories_id 
 INNER JOIN categories_description cd ON cd.categories_id=c.parent_id
 GROUP BY cd.categories_id
于 2013-09-10T11:33:25.093 回答