mySQL从类别及其子类别中选择项目

时间:2013-02-11 03:45:46

标签: mysql parent categories

我有两个表项目和类别。类别表是自联合表。

项目表包含以下列 ID,Item_Name,CategoryID

类别表包含以下列 CATID,category_name,parent_ID

我需要选择列在类别下的项目和此主要类别的子类别但不起作用。这是mysql,它只返回sub。

Select * from 
 Items A
where 
 A.CategoryID in(select CATID from categories 
    where CATID= %value% or parent_ID=%value%)    

2 个答案:

答案 0 :(得分:2)

由于字段是相关的,因此请使用连接。如果您在“类别”表中有一些一对多的关系,请使用select distinct

select distinct Items.*
from Items
join Categories as self_cat
    on (Items.CategoryID = self_cat.CATID)
left join Categories as parent_cat
    on (self_cat.parent_id = parent_cat.CATID)
where %value% in (self_cat.CATID, parent_cat.CATID)

答案 1 :(得分:1)

使用tbl_category表的自我加入然后使用tbl_item进行内部联接

SELECT i.ID as ItemID,
           i.item_name,
           c.catid AS categoryID,
           c.category_name AS categoryName,
           p.catid AS parentCategoryID,
           p.category_name as ParentCategoryName
 FROM tbl_item i
 INNER JOIN tbl_category p ON  p.catid = i.category_id 
 INNER JOIN tbl_category c ON  c.parent_id = p.catid 
 WHERE %value%  = p.cat_id  OR  %value%  = c.cat_id
相关问题