mysql - 选择类别树中某处具有 category_id 的记录

标签 mysql sql

我正在显示一棵类别树,在每个分支旁边我想要统计相同级别或更低级别的列表的数量。

所有列表都有一个处于最低类别级别的 catid。也就是说,如果有较低的类别级别可用,则您不能将特定的 catid 应用于列表。

例如,在下面的“列表”表中,您找不到 catid = 24 的列表,因为这还不是该分支树中的最低级别。

在我的类别数据库中,最多有 4 个级别 (0-3)。

这是表格:

all_categories(表格)

record_id  parent_category_id   parent_id  title        level
--------------------------------------------------------------------- 
24         NULL                 NULL       Real Estate  0
5915       24                   24         Residential  1
7569       5915                 24         For sale     2

列表(表格)

record_id    cat_id
--------------------
1            7569
2            8847

因此,我的 HTML 类别树应该如下所示:

HTML

Categories              Listing count
-------------------------------------
24                      1
  5915                  1
    7569                1

因此,在我的 html 和 jQuery 代码中,我将任何级别的特定 catid 传递给查询,它应该找到处于或低于该级别的列表。

我已经尝试了几个小时,但到目前为止我的努力不值得展示。但无论如何我都会...

编辑:到目前为止我的努力(别笑,经过数小时尝试不同的事情后它变得困惑):

select l.record_id 
from listings l
where catid in (
    select record_id 
    from all_categories 
    where record_id = 5915)
or catid in (
    select parent_category_id 
    from all_categories 
    where parent_category_id = 5915)
or catid in (
    select parent_id 
    from all_categories 
    where parent_id = 5915)

最佳答案

child 的 0 级 parent_id 保存在“all_categories”表中。

所以一个 child 可以通过他们共同的 parent_id 链接到其他 child 。
然后同时包含0级。

困难在于给定的 child ID 不在“列表”表中。
因此,要检索该列表 record_id,它必须通过类别。

可以找到rextester 上的测试here

SELECT 
cat.record_id as catId, 
pl.listId AS ListingCount,
cat.level
FROM 
(
    SELECT 
     cat1.parent_id, 
     MAX(list.record_id) AS listId
    FROM all_categories AS cat1
    JOIN all_categories AS cat2 ON cat2.parent_id = cat1.parent_id
    JOIN listings list ON list.cat_id = cat2.record_id
    WHERE cat1.record_id = 5915
    GROUP BY cat1.parent_id
) AS pl
LEFT JOIN all_categories AS cat ON (cat.parent_id = pl.parent_id OR cat.record_id = pl.parent_id)
ORDER BY cat.record_id, cat.level;

结果:

catId   ListingCount    level
24      1               0
5915    1               1
7569    1               2

“级别”也包含在查询中,因为它可用于在 HTML 中生成该类别树。

请注意,如果“listings”表只包含级别 0 的 cat_id,则可以大大简化查询

关于mysql - 选择类别树中某处具有 category_id 的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53575163/

相关文章:

php - 在 PHP 中将数据从 SQL 转换为字符串

php - 如何将具有where条件的多个表转储到单个文件中

SQL查询根据ID将多行合并为一行,同时将其他值保留在同一行中?

sql - Once SQL 命令判断真或假

Mysqldump 不工作 : "command not found"

python - 在 PyQt5 中的 MySQL 表上执行 QSqlQuery 时出现问题

php - 如何通过 SQL 在 PHP 中创建动态表

php - 无法从 MySQL 表中检索数据

sql - libpq 对于大型(2000 万条记录)数据库来说非常慢

sql - 选择类别属于层次结构中任何类别的产品