Solved

MYSQL Record Number

Posted on 2016-08-31
3
54 Views
Last Modified: 2016-09-19
I want to be able to get the record number within my query.

I have a simple table
ID  NAME
11  steve
82  bob
32  peter


I can get the rank number of the query like this:

SELECT *, @rownum := @rownum + 1 AS rank
FROM table, (SELECT @rownum := 0) r
ORDER BY id

returns:
ID  NAME rank
11  steve  1
82  bob    2
32  peter  3



BUT if I run a query like this:

SELECT *, @rownum := @rownum + 1 AS rank
FROM table, (SELECT @rownum := 0) r
WHERE name = "bob"
ORDER BY id

Its returns:
ID  NAME rank
82  bob    1



But I want it to still return rank = 2.... the position in the db.


Can anyone help.

Steve
0
Comment
Question by:sjtinsley83
  • 2
3 Comments
 
LVL 49

Accepted Solution

by:
Ryan Chong earned 500 total points
ID: 41777662
try this?
select * from
(
SELECT *, @rownum := @rownum + 1 AS rank
FROM Table1, (SELECT @rownum := 0) r
) r
where name = 'bob'
ORDER BY id

Open in new window

1
 

Author Closing Comment

by:sjtinsley83
ID: 41777673
Worked first time!! Thanks
0
 

Author Comment

by:sjtinsley83
ID: 41805370
Hi Ryan,

I am suddenly getting issues with this query. It is giving me the number plus 1.
I dont completely understand how this works.

Any ideas??

Steve
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

This article describes some very basic things about SQL Server filegroups.
Many companies are looking to get out of the datacenter business and to services like Microsoft Azure to provide Infrastructure as a Service (IaaS) solutions for legacy client server workloads, rather than continuing to make capital investments in h…
Video by: Steve
Using examples as well as descriptions, step through each of the common simple join types, explaining differences in syntax, differences in expected outputs and showing how the queries run along with the actual outputs based upon a simple set of dem…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now