我有这张桌子:
item_id item_name item_status visibility "item_number"
6 foo6 3 1 4
5 foo5 2 1 3
4 foo4 1 0 x
3 foo3 3 1 2
2 foo2 2 0 x
1 foo1 1 1 1
这些项目是visibility
字段的“仁慈”。如果我想将可见性设置为0,例如items_id
的2和4,我希望“item_number
”(不是真正的列)进行相应的调整。
如果我要选择item_status
为2的项目,则会返回状态为2的项目,但“已调整”项目的item_number
为3。
这可能在PHP + MySQL吗?
通常您会将item_id
作为项目的ID。但是,问题是即使你删除了一个项目,MySQL自动增量仍然会继续(在这种情况下,它是visibility
列)。因此,如果我最近添加了项目6然后删除了项目2和4,则下一个item_id
将有一个7,但数据库中只有4个项目。对于这些“可见”项目,我希望项目编号为1,2,3和4而不是ID 1,3,5和6.
另外,如果我要获得item_status
为2的项目,通常会得到item_id
为5的项目,但该项目在数据库中仅为第3项(由于之前的原因)删除的项目)所以我想返回3。
答案 0 :(得分:2)
SELECT item_id, item_name, item_status, visibility,
CASE WHEN (visibility !=0) THEN @itemCount := @itemCount +1 END AS item_number
FROM items
JOIN (SELECT @itemCount :=0) AS vars
ORDER BY item_id
这将导致:
+---------+------------+-------------+------------+-------------+
| item_id | item_name | item_status | visibility | item_number |
+---------+------------+-------------+------------+-------------+
| 1 | Banana | 1 | 1 | 1 |
| 2 | Apple | 4 | 1 | 2 |
| 3 | Orange | 3 | 1 | 3 |
| 4 | Strawberry | 2 | 0 | NULL |
| 5 | Pear | 5 | 1 | 4 |
| 6 | Plum | 4 | 0 | NULL |
| 7 | Grape | 2 | 0 | NULL |
| 8 | Peach | 3 | 1 | 5 |
| 9 | Papaya | 6 | 1 | 6 |
| 10 | Melon | 7 | 0 | NULL |
+---------+------------+-------------+------------+-------------+
答案 1 :(得分:0)
想出来它(不幸的是)需要一个嵌套查询:
SELECT * //select all columns
FROM ( //from a derived table
SELECT
b.*, //select all columns
@itemCount:=@itemCount +1 AS item_number //and a counter column named item_number
FROM items b, (SELECT @itemCount :=0) r //from items table and with the counter column initialized as 0
WHERE visibility != 0 //select only those visible
) AS b
LIMIT 0, 30 //limit to 30 rows
它做了什么:
所以,如果我想从1000开始显示30行,它将显示从1000开始的30个可见项目,计数从1000开始
的引用: