我有的:
分级列出的类别表:
产品表。该栏category_id
是指category.id
:
我正在尝试做的事情:
我正在尝试设计一个查询,该查询将计算具有指定lft
和rgt
值的类别产品。
例如:在lft
=2
和rgt
=11
之间有 3 个“直接子类别”,其 ID 为3
,4
和5
. 请注意,wireless
子类别不包括在内,因为它不是范围内的直接子类别lft
,rgt
但该子类别的产品将被视为其直接子类别的一部分,headphone
如下图所示。Headphone
有一个直接产品,而另一种产品与其wireless
子类别相关。
结果应该是:
我设法进行查询,检索指定lft
和rgt
值内的直接子类别。
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
当=2
和rgt
=时,此查询将检索上一张图片中的子类别,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');