1

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

我目前的查询是:

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
4

2 回答 2

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

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

"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"
于 2012-10-16T02:59:15.907 回答
1

ok, i've made a number of assumptions here, which may or may not be true and depend on your schema and data, but something like this should work:

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;

this assumes:

  • if a category has no parent, the lc_parent column value is 0
  • there are only 2 levels of categories - ie. parents & children, no grandchildren
  • you only want to show results for parent categories

let me know if any of these assumptions are incorrect and i can adjust the query.

于 2012-10-15T11:57:13.387 回答