TAGS :Viewed: 12 - Published at: a few seconds ago

[ MySQL query works in Workbench, but not within code ]

Using MySQL 5.5.30, for a table, purchase_order_product (MyISAM), that has the following records:

+----------+------------------+
| order_id | order_product_id |
+----------+------------------+
|       98 |                1 |
|       99 |               14 |
|       99 |               15 |
|      100 |               16 |
|      100 |               17 |
|      100 |               18 |
|      101 |               19 |
|      102 |               20 |
+----------+------------------+

When I run the following query from 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;

I get the following output:

+----------+------------------+--------+--------+
| 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 |
+----------+------------------+--------+--------+

My desired goal is the value of rownum, which is fine and as expected so far...

HOWEVER, when I run the query from within my PHP code OR from the mysql command line against the same database using the same db user, I get the following output:

+----------+------------------+--------+--------+
| 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 |
+----------+------------------+--------+--------+

As you can see, rownum is always 1!

I have search extensively for a solution to this perplexing issue, to no avail. Does anyone have any idea what may be going on? Am I doing something wrong?

Answer 1


You need to initialize the variable:

 SET @RUNNING:=0;
 SET @PREVIOUS:=0;

This must be done before your query and in the same mysql session.