如何获得父子类别项目?

时间:2012-10-14 16:37:45

标签: php mysql codeigniter

我基本上试图制作一个类别列表,其中包含一系列类别及其子类别。

我目前的查询是:

SELECT category.lc_name AS name,COUNT(listings.ls_cat_id) AS post_count
FROM listings_categories AS category
LEFT JOIN listings ON listings.ls_cat_id = category.lc_id 
GROUP BY category.lc_id ORDER BY name ASC

它的效果非常好,但我希望将子类别项或帖子数添加到其父类别中。

例如:

id | category | parent | Count
1      Auto        0       3
2      Auto A      1       1
3      Auto B      1       1
4      Auto C      1       1

我只使用一个查询在mysql中可以做什么?

表格结构

listings - ls_id,ls_cat_id,ls_title
listings_categories - lc_id,lc_parent,lc_name

2 个答案:

答案 0 :(得分:1)

好吧,我在这里做了一些假设,这可能是也可能不是真的,取决于你的架构和数据,但这样的事情应该有效:

select numListings, lc_name from
(
    SELECT
    IF(lc_parent = 0, lc_id, lc_parent) AS lc_parent_id, COUNT(ls_id) as numListings
    FROM listings_categories
    LEFT JOIN listings ON listings.ls_cat_id = listings_categories.lc_id
    group by lc_parent_id
) catList
inner join listings_categories on catList.lc_parent_id = listings_categories.lc_id;

这假定:

  • 如果某个类别没有父级,则lc_parent列值为0
  • 只有两个级别的类别 - 即。父母和父母孩子,没有孙子
  • 您只想显示父类别的结果

如果有任何这些假设不正确,请告诉我,我可以调整查询。

答案 1 :(得分:1)

我刚刚找到了正确的答案。

SELECT category.lc_name AS name,

COUNT(listings.ls_cat_id) + (

    SELECT COUNT(listings.ls_cat_id) FROM listings_categories AS subcategory
    LEFT JOIN listings ON listings.ls_cat_id = subcategory.lc_id
    WHERE category.lc_id = subcategory.lc_parent
) AS count

FROM listings_categories AS category
LEFT JOIN listings ON listings.ls_cat_id = category.lc_id
GROUP BY category.lc_id ORDER BY name ASC

我刚刚将当前计数添加到另一个select语句中,该语句将当前类别ID与新select语句的父类别id匹配。

"name"  "count"
"auto detailing"    "0"
"auto insurance"    "1"
"auto mechanic" "1"
"auto painting" "0"
"auto sales and parts"  "0"
"automotive"    "3"
"business"  "0"
"dental clinics"    "0"
"fashion"   "0"
"health and medicine"   "0"
"health insurance"  "0"
"home and garden"   "0"
"hospital"  "0"
"jobs and employment"   "0"