2

我有 2 个用于项目和类别的表。类别表是自联合表。

项目表具有以下列 ID、Item_Name、CategoryID

类别表具有以下列 CATID、category_name、parent_ID

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

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

2 回答 2

2

Since the fields are related, use joins. If you have some one-to-many relationships going on with the Categories table, use 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)
于 2013-02-11T04:13:51.747 回答
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
于 2013-02-11T04:22:28.407 回答