Reputation: 27899
I have a table in MySQL database as shown in the following snap shot.
I need to obtain a current row number based on rating_id
(primary key) given in each group of products.
Currently the following SQL obtains a row number based on rating_id
from all rows in the table.
SELECT rownum
FROM (SELECT @rownum := @rownum + 1 AS rownum,
tbl.rating_id
FROM rating tbl,
(SELECT @rownum := 0)t
ORDER BY tbl.rating_id DESC)t
WHERE rating_id = ?
How to restrict this query to a specific group of products (prod_id
)?
In other words, how to get a row number from a group of rows which is specific a particular product (prod_id
)?
Upvotes: 2
Views: 85
Reputation: 24134
I guess you need to count each group of PROD_ID separately. In this case you should add one more user defined variable to store previous PROD_ID and reset @rownum
when new PROD_ID group starts.
SELECT rownum,rating_id,prod_id
FROM (SELECT if(prod_id=@prev_prod,@rownum := @rownum + 1,@rownum:=1)
AS rownum,
tbl.rating_id,
tbl.prod_id,
@prev_prod:=prod_id
FROM rating tbl,
(SELECT @rownum := 1,
@prev_prod:=NULL)t
ORDER BY tbl.prod_id)t
WHERE rating_id = ?
Upvotes: 2