使用MySQL 5.5.30,对于具有以下记录的表buy_order_product(MyISAM):
+----------+------------------+
| order_id | order_product_id |
+----------+------------------+
| 98 | 1 |
| 99 | 14 |
| 99 | 15 |
| 100 | 16 |
| 100 | 17 |
| 100 | 18 |
| 101 | 19 |
| 102 | 20 |
+----------+------------------+
当我从MySQL Workbench 5.2.47 CE运行以下查询时:
SELECT pop.order_id, pop.order_product_id,
@RUNNING:=IF(@PREVIOUS = pop.order_id, @RUNNING, 0) + 1 AS rownum,
@PREVIOUS:=pop.order_id as previd
FROM purchase_order_product pop
ORDER BY pop.order_id , pop.order_product_id ASC;
我得到以下输出:
+----------+------------------+--------+--------+
| order_id | order_product_id | rownum | previd |
+----------+------------------+--------+--------+
| 98 | 1 | 1 | 98 |
| 99 | 14 | 1 | 99 |
| 99 | 15 | 2 | 99 |
| 100 | 16 | 1 | 100 |
| 100 | 17 | 2 | 100 |
| 100 | 18 | 3 | 100 |
| 101 | 19 | 1 | 101 |
| 102 | 20 | 1 | 102 |
+----------+------------------+--------+--------+
我期望的目标是rownum的价值,这是好的,并且到目前为止一样......
然而,当我从我的PHP代码中运行查询或使用相同的db用户从mysql命令行对同一个数据库运行时,我得到以下输出:
+----------+------------------+--------+--------+
| order_id | order_product_id | rownum | previd |
+----------+------------------+--------+--------+
| 98 | 1 | 1 | 98 |
| 99 | 14 | 1 | 99 |
| 99 | 15 | 1 | 99 |
| 100 | 16 | 1 | 100 |
| 100 | 17 | 1 | 100 |
| 100 | 18 | 1 | 100 |
| 101 | 19 | 1 | 101 |
| 102 | 20 | 1 | 102 |
+----------+------------------+--------+--------+
如你所见,rownum总是1!
我已广泛搜索解决这个令人困惑的问题,但无济于事。有谁知道可能会发生什么?我做错了吗?
答案 0 :(得分:2)
您需要初始化变量:
SET @RUNNING:=0;
SET @PREVIOUS:=0;
这必须在查询之前和同一个mysql会话中完成。