我正在尝试编写一个mysql命令来选择每个类别中的6个项目,如最右侧的“category”字段所示。我基本上想要为每个类别值选择6条记录。
下面是从SELECT *命令到数据库
的前几行的示例myArray = myArray.filter(function(element) {
return element.state.name !== 'object #1';
})
这是我正在使用的命令。我正在使用while循环继续运行,直到它运行了多次类别(在这种情况下为3),每次循环运行时从每个类别中选择6个项目
+--------------------------------------+------------------------------------+--------------+--------+--------------+---------------------------+
| imageLocation | productName | manufacturer | price | availability | category |
+--------------------------------------+------------------------------------+--------------+--------+--------------+---------------------------+
| ./images/Strawberry_Pi_3_Model_B.jpg | Camera Module XF181 | Toro | 35.99 | 10 | Strawberry Pi |
| ./images/Strawberry_Pi_3_Model_B.jpg | Strawberry Pi Extension Kit SG218 | Apollo | 22.99 | 4 | Popular Items |
| ./images/Strawberry_Pi_Zero.jpg | Strawberry Pi Extension Kit AU252 | Gorella | 194.99 | 1 | Strawberry Pi Accessories |
| ./images/Strawberry_Pi_2_Model_B.jpg | Strawberry Pi Case ZM942 | Corona | 182.99 | 7 | Popular Items |
| ./images/Strawberry_Pi_2_Model_B.jpg | Compute Module Kit GP664 | Corona | 16.99 | 1 | Strawberry Pi Accessories |
| ./images/Strawberry_Pi_3_Model_B.jpg | Camera Module CL638 | Apollo | 256.99 | 7 | Strawberry Pi Accessories |
我收到错误
SET x = 0; WHILE ( x < COUNT(SELECT UNIQUE category FROM PRODUCTS) DO SELECT * FROM Products WHERE category IN (SELECT UNIQUE category FROM Products LIMIT x-1,1) LIMIT 6; SET x = x + 1; END WHILE;
我想要的输出示例是
ERROR 1193 (HY000): Unknown system variable 'x'
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHILE ( x < COUNT(SELECT UNIQUE category FROM PRODUCTS) DO SELECT * FROM Product' at line 1
ERROR 1193 (HY000): Unknown system variable 'x'
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'END WHILE' at line 1
答案 0 :(得分:1)
SELECT *
FROM
(SELECT *,
@category_rank := IF(@current_category = category, @category_rank + 1, 1) AS category_rank,
@current_category := category
FROM Products
ORDER BY category
) ranked
WHERE category_rank <= 6;