【发布时间】:2018-11-28 09:50:55
【问题描述】:
我想选择每个类别,并计算该类别及其所在的每个子类别中的每个产品的数量。
此 SQL QUERY 返回 ID 为 X 的类别所拥有的产品数量,其中包含其子类别产品。
SELECT
count(*)
FROM productos
INNER JOIN categorias
ON categorias.id = productos.categoria_id
WHERE productos.categoria_id IN (select id
FROM (SELECT * FROM categorias
ORDER BY parent, id) products_sorted,
(SELECT @pv := X) initialisation
WHERE find_in_set(parent, @pv)
AND length(@pv := concat(@pv, ',', id))
OR id = @pv)
AND productos.active IS TRUE AND categorias.active IS TRUE
ORDER BY categorias.pos) as productos
现在我正在尝试使用他们的产品数量来获取我拥有的每个类别,这是我的 SQL,但它在字段列表中显示未知表 cats。我也试过没有别名。我想我不能在第二个选择中使用它。那么,我该怎么做呢?
SELECT
cats.*,
(SELECT
count(*)
FROM productos
INNER JOIN categorias
ON categorias.id = productos.categoria_id
WHERE productos.categoria_id IN (select id
FROM (SELECT * FROM categorias
ORDER BY parent, id) products_sorted,
(SELECT @pv := cats.id) initialisation
WHERE find_in_set(parent, @pv)
AND length(@pv := concat(@pv, ',', id))
OR id = @pv)
AND productos.active IS TRUE AND categorias.active IS TRUE
ORDER BY categorias.pos) as productos
FROM categorias AS cats ORDER BY cats.parent, cats.pos
表格
+----------------------+
| Catrgorias |
+----------------------+
| id (int 11) |
+----------------------+
| nombre (varchar 255) |
+----------------------+
| parent (int 11) |
+----------------------+
| active (tinyint 11) |
+----------------------+
| pos (int 11) |
+----------------------+
+----+------------+--------+
| id | nombre | parent |
+----+------------+--------+
| 1 | Cat1 | NULL |
+----+------------+--------+
| 2 | Cat2. | NULL |
+----+------------+--------+
| 3 | SubCat1 | 1 |
+----+------------+--------+
| 4 | SubCat2 | 2 |
+----+------------+--------+
| 5 | SubSubCat1 | 3 |
+----+------------+--------+
+-----------------------+
| Productos |
+-----------------------+
| id (int 11) |
+-----------------------+
| name (varchar 255) |
+-----------------------+
| description (text) |
+-----------------------+
| image (varchar 255) |
+-----------------------+
| price (decimal 11,2) |
+-----------------------+
| categoria_id (int 11) |
+-----------------------+
| pos (int 11) |
+-----------------------+
| active (tinyint 11) |
+-----------------------+
【问题讨论】: