Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to query a table created by another query?

So I have a table, users, with user Balances and IDs.
With the below query, I get the table I need – which sorts the users by their balance.

SET @row_num=0; SELECT (@row_num:=@row_num+1) AS serial_num, ID, Balance FROM users ORDER BY Balance DESC; – which returns the following table:

Resulting MYSQL table

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How would I find the serial_num of a specific user from the above table by ID?

I’ve tried SELECT * FROM ( the query above ) WHERE ID = "..."; but I must be getting something wrong with the syntax and I don’t quite understand how I would implement a sub-query here.
Cheers

>Solution :

You had actually just 1 like mistake which lead to an uninitialized variable. Replace

SET @row_num=0;

with

SET @row_num:=0;

A little shorter version which can be run in one query would be:

SELECT * 
FROM
(
   SELECT ID, Balance, @row := @row + 1 AS serial_num
   FROM users 
   CROSS JOIN (SELECT @row := 0) r
   ORDER BY Balance DESC
) tmp
WHERE serial_num = 2

SQLFiddle demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading