【问题标题】:Querying items from a category从类别中查询项目
【发布时间】:2020-09-14 12:47:56
【问题描述】:

这里是 DB 菜鸟。我想要具有多级嵌套(可能是 3 到 4 个)类别的类别。例如:服装 > 男装 > 夏装

所以我做了递归分类表。

+---------------------------------+
| CATEGORIES                      |
+---------------------------------+
| id <PK>                         |
| parent_id <FK -> CATEGORIES.id> |
| name                            |
+---------------------------------+

+-----------------------------------+
| ITEMS                             |
+-----------------------------------+
| id <PK>                           |
| category_id <FK -> CATEGORIES.id> |
| name                              |
+-----------------------------------+

问题是我不知道如何查询第一级父类别下的所有项目。

例如,ITEM 1 低于 2 级,Men's clothing (id: 2)ITEM 2 低于 3 级,Summer wears (id: 3)

当我查询Clothing (id: 1) 下的项目时,我想查看所有ITEM 1ITEM 2,这是Men's clothingSummer wears 的父项。

我该怎么做?

堆栈:Node.js、Postgres、Knex.js、TypeScript

【问题讨论】:

    标签: javascript sql postgresql join recursive-query


    【解决方案1】:

    您可以使用递归查询列出输入类别的所有子项,然后使用它来过滤项目:

    with recursive cats as (
        select id from categories where name = ?
        union all
        select c.id 
        from categories c
        inner join cats p on p.id = c.parent_id
    )
    select i.*
    from items i
    inner join cats c on c.id = i.category_id
    

    应将问号替换为您要展示其项目的(父)类别的名称(在您的示例中为'Clothing')。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-30
      • 1970-01-01
      • 1970-01-01
      • 2021-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-26
      • 2023-03-30
      相关资源
      最近更新 更多