mySQL从类别及其子类别中选择项目
我有两个表的项目和类别。类别表是自联接表 Item表具有以下列 标识、项目名称、类别ID “类别”表有以下列 CATID、类别名称、父项ID 我需要选择在一个类别和这个主类别的子类别下列出但不起作用的项目。这里是mysql,它只返回submySQL从类别及其子类别中选择项目,mysql,parent,categories,Mysql,Parent,Categories,我有两个表的项目和类别。类别表是自联接表 Item表具有以下列 标识、项目名称、类别ID “类别”表有以下列 CATID、类别名称、父项ID 我需要选择在一个类别和这个主类别的子类别下列出但不起作用的项目。这里是mysql,它只返回sub Select * from Items A where A.CategoryID in(select CATID from categories where CATID= %value% or parent_ID=%value%)
Select * from
Items A
where
A.CategoryID in(select CATID from categories
where CATID= %value% or parent_ID=%value%)
因为字段是相关的,所以使用联接。如果类别表中存在某种一对多关系,请使用
选择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)
尝试使用
tbl\u类别的自联接,然后使用tbl\u项目进行内部联接
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