【问题标题】:mySQL Select items from a category and its subcategoriesmySQL 从一个类别及其子类别中选择项目
【发布时间】:2013-01-26 04:02:33
【问题描述】:

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

项目表具有以下列 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%)    

【问题讨论】:

    标签: mysql parent categories


    【解决方案1】:

    由于字段是相关的,请使用连接。如果您与 Categories 表有一些一对多的关系,请使用 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)
    

    【讨论】:

      【解决方案2】:

      尝试使用tbl_category 表的self join,然后使用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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-23
        相关资源
        最近更新 更多