明智地对产品进行分类

时间:2014-08-16 14:36:22

标签: php mysql

我有三个表产品,类别

enter image description here

和product_category。

enter image description here

如何对产品进行分类,明确类别并获取类别名称以及将表product_category连接到类别,因为product_category只有cat_id且没有类别名称。

Cell Pones
Cell Pones 1
Cell Pones 2
Cell Pones 3

Books
Book 1
Book 2
Book 3

2 个答案:

答案 0 :(得分:1)

获取所有产品/类别组合,并按类别名称对其进行排序。显然,产品和类别可能不止一次出现,因为关系产品类别是多对多的。

SELECT p.prd_name, p.prd_price, c.cat_name
FROM Product p
JOIN Product_category pc ON p.prd_id = pc.prd_id
JOIN Category c ON c.cat_id = pc.cat_id
ORDER BY c.cat_name

答案 1 :(得分:0)

这不是一个真正的关系"输出,因为列具有不同的含义,并且行的位置很重要(SQL结果集和表通常表示无序集)。但是,你可以做到。

select name
from ((select cat_id, cat_name as name, 0 as sortorder
       from category_table
      ) union all
      (select cat_id, prd_name, 1 as sortorder
       from product_category pc join
            product p
            on pc.prd_id = p.prd_id
      )
     ) n
order by cat_id, sortorder;
相关问题