2

我有的:

分级列出的类别表: 类别表

产品表。该栏category_id是指category.id在此处输入图像描述

我正在尝试做的事情:

我正在尝试设计一个查询,该查询将计算具有指定lftrgt值的类别产品。
例如:在lft=2rgt=11之间有 3 个“直接子类别”,其 ID 为3,45. 请注意,wireless子类别不包括在内,因为它不是范围内的直接子类别lftrgt但该子类别的产品将被视为其直接子类别的一部分,headphone如下图所示。Headphone有一个直接产品,而另一种产品与其wireless子类别相关。

结果应该是:

在此处输入图像描述

我设法进行查询,检索指定lftrgt值内的直接子类别。

    SELECT node.name,node.id, (COUNT(parent.name) - 1) AS depth
    FROM category AS node,
        category AS parent
    WHERE node.lft BETWEEN parent.lft AND parent.rgt
        AND parent.lft BETWEEN {$lft} AND {$rgt}
    GROUP BY node.name
    HAVING depth = 1
    ORDER BY node.lft

lft当=2rgt=时,此查询将检索上一张图片中的子类别,11但它缺少计数。

我已经尝试了很长一段时间来正确获得该结果表,这就是我想出的,但不幸的是,由于某种我不知道的原因,它不能很好地工作。感谢您对此的任何帮助。

            SELECT parent.name, COUNT(product.category_id)
    FROM category AS node1 ,
            product, (
                SELECT node.name,node.id,node.lft,node.rgt, (COUNT(parent.name) - 1) AS depth
                FROM category AS node,
                    category AS parent
                WHERE node.lft BETWEEN parent.lft AND parent.rgt
                    AND parent.lft BETWEEN {$lft} AND {$rgt}
                GROUP BY node.name
                HAVING depth = 1
                ORDER BY node.lft
            ) as parent
    WHERE node1.lft BETWEEN parent.lft AND parent.rgt
            AND node1.id = product.category_id
    GROUP BY parent.lft
    ORDER BY parent.lft

更新:我试图制作 SQL 小提琴,但我得到了大量的错误列表:

    CREATE TABLE category 
        (
         id int auto_increment primary key, 
         name varchar(20), 
         lft varchar(20),
          rgt varchar(20)
        );

    INSERT INTO category
    (name, lft,rgt)
    VALUES
    ('ELECTRONICS','1','18'),
    ('TV & audio','2','11'),
    ('Home theater','3','4'),
    ('Blu-ray','5','6'),
    ('Headphone','7','10'),
    ('Wireless','8','9'),
    ('Gaming','12','17'),
    ('Game consoles','13','14'),
    ('Video games','15','16');

    CREATE TABLE product 
        (
         id int auto_increment primary key, 
         name varchar(20), 
         category_id varchar(20)
        );
    INSERT INTO product
    (category_id, name)
    VALUES
    ('4','Sony Blu-ray player'),
    ('5','Beats Solo HD'),
    ('6','Beats Solo HD wireless'),
    ('8','PlayStation'),
    ('8','Xbox');       
4

1 回答 1

0

会不会比这样的简单(?):

SELECT category.name, COALESCE(C.total,0) as products
  FROM category 
  LEFT JOIN
    (SELECT category_id, count(*) as total FROM product GROUP BY category_id) AS C
  ON C.category_id = category.id
  WHERE category.lft > @min_range AND category.rgt < @max_range

如果您忽略“噪音”,这只是类别表和每个类别的产品数量之间的左连接(保留没有产品的类别)。

使用您的测试用例,它会产生:

+--------------+----------+
| name         | products |
+--------------+----------+
| Home theater |        0 |
| Blu-ray      |        1 |
| Headphone    |        1 |
| Wireless     |        1 |
+--------------+----------+
4 rows in set (0.00 sec)

如您所见,它产生的无线结果未出现在您的预期结果中,但根据我对您对问题的描述的理解,它应该存在。

于 2013-08-10T09:54:59.140 回答