2

Lets say I have list of users in my user table like below. I need to find the count of users from my table until the userid is equal to 100.

So here the answer is (3). But how can i find this is MySQL query. Any idea?

userid    name
---------------
10        aaa
30        bbb
100       ccc
60        ddd
5
  • Is the UserId field indexed anyhow? Jul 13, 2016 at 14:50
  • Or is your query ordered by any other field? Jul 13, 2016 at 14:51
  • if your table only has 2 columns, why userid is not sorted?
    – CSK
    Jul 13, 2016 at 15:05
  • Actually my requirement is different. I suppose to find the user's rank from the score table. Scores not is order, so based on order by score DESC, i need to find the user rank. Here i have the userid. So by passing the userid i need this condition.
    – Naren
    Jul 13, 2016 at 15:12
  • Isn't userid supposed to be unique across the table?
    – 1000111
    Jul 13, 2016 at 15:18

2 Answers 2

1

This is one of the work around to achieve your expectation.

SET @row_number:=0;

SELECT A.row_number FROM (
    SELECT Userid, name, @row_number:=@row_number+1 AS row_number  
    FROM UserDetail
) AS A
WHERE A.Userid = 100;

Working DEMO

In case if the UserId is the not the unique id and it can repeat, you may add the ORDER BY with LIMIT 1

SET @row_number:=0;

SELECT A.row_number FROM (
    SELECT Userid, name, @row_number:=@row_number+1 AS row_number  
    FROM UserDetail
) AS A
WHERE A.Userid = 100
ORDER BY A.row_number
LIMIT 1;

Working DEMO

Sample execution with given data:

--DROP TABLE UserDetail;

CREATE TABLE UserDetail (Userid INT,  name VARCHAR (50));

INSERT INTO UserDetail (Userid, name) VALUES
(10 , 'Aaa'),
(30 , 'Bbb'),
(100, 'Ccc'),
(60 , 'ddd');

SET @row_number:=0;

SELECT A.row_number FROM (
    SELECT Userid, name, @row_number:=@row_number+1 AS row_number  
    FROM UserDetail
) AS A
WHERE Userid = 100;
2
  • This doesn't work if there are more than one instances of UserID = 100, you will need to choose the min value. But great solution! We must have been working on this at the exact same time!
    – EoinS
    Jul 13, 2016 at 14:57
  • @EoinS: Thought of the UserId is the unique, anyway handled the duplicate Userid by ORDER BY with LIMIT 1
    – Arulkumar
    Jul 14, 2016 at 9:44
0

This is difficult to do in MySql as the 'first' instance of a number can be difficult to pin down.

One way to resolve this would be to create row numbers, then choose the minimum row number with Userid = 100

select min(row_number) from
(
SELECT @rownum:=@rownum + 1 as row_number, 
       p.*
FROM p,
(SELECT @rownum := 0) r
  ) g
where userid = 100

Here is a functional example

1
  • Awesome. Thank you so much :).
    – Naren
    Jul 13, 2016 at 15:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.