我想选择每一个类别的计数,每个产品在这个类别和每个子类别它是。
此sql查询返回一个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
table
+----------------------+
| 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) |
+-----------------------+
1条答案
按热度按时间cgh8pdjw1#
在错误消息中是否有行被感染?我认为问题是
我会改变的
我不知道这是否是你的解决方案,但在你的查询中我看不到其他结构性问题。
为了得到同样的结果,我写了这样的东西,检查它是否有效(你确定你在评论中写的数字吗?)