类别和子类别和产品查询无法按预期工作

时间:2013-09-10 11:28:58

标签: mysql sql

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

我的查询使用了5个表:

  1. 产品 - 此表格包含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字段。
  6. 这是我的问题:

    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
    

1 个答案:

答案 0 :(得分: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