【问题标题】:How to show only categories with products in shopping cart如何仅显示购物车中包含产品的类别
【发布时间】:2013-08-17 09:03:08
【问题描述】:

在购物车中产品类别树以嵌套集合形式定义为

create table  artomlii (
  artomaliik serial primary key,
  treeparent integer references artomlii,  -- parent or null if root node
  categoryname char(50) );

树的最大深度为 5。

树中的产品定义为

create table artomadu (
  artomaliik integer primary key references artomlii not null,
  productid char(20) primary key not null
  )

使用查询显示购物车主页根目录

select * from artomlii where treeparent is null

根据登录用户,某些根目录可以为空,它们不包含 任何子类别中的任何产品。因为此自定义过滤器应用于 artomadu 表。

此查询也显示空的根类别。 如何解决此问题,以便仅显示在其任何子类别中至少包含一个产品产品的根类别?

可以用 WITH RECURSIVE 还是其他想法?

【问题讨论】:

    标签: sql asp.net-mvc-3 postgresql tree shopping-cart


    【解决方案1】:
    with recursive cte as (
        select a.artomaliik, a.categoryname, a.artomaliik as treeparent
        from artomlii as a
        where a.treeparent is null
    
        union all
    
        select c.artomaliik, c.categoryname, a.artomaliik as treeparent
        from artomlii as a
            inner join cte as c on c.treeparent = a.treeparent
    )
    select distinct
        c.artomaliik, c.categoryname
    from cte as c
    where
        exists (select * from artomadu as a where a.artomaliik = c.treeparent)
    

    sql fiddle demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-04
      • 1970-01-01
      • 2013-05-02
      • 2013-06-07
      相关资源
      最近更新 更多