我正在尝试使用类别表中的单个查询获取所有类别和子类别以及产品,该类别表具有子类别和产品表的parent_id。但我没有得到确切的结果。 我不知道我做错了什么。
我的查询使用了5个表:
products_id
字段和其他详细信息products_name
和products_id
字段categories_id
字段相关联的products_id categories_id
及其他字段和parent_id
字段categories_id
和categories_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
答案 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