We help IT Professionals succeed at work.

How to get the id that came BEFORE the provided id

tjyoung
tjyoung asked
on
229 Views
Last Modified: 2013-01-08
Hi,
I have some code that supplies an $id and an $account_id for a record in a table

I need to be able to query using those what the PREVIOUS id is that is associated with that account_id.

So in other words, what was the last id for a record that was created before the one that is provided under that account _id.

Its not simply one less than the current id (LIMIT 1, 1) because there may be others in between that are associated to other accounts.

Make any sense?
Comment
Watch Question

Guy Hengel [angelIII / a3]Billing Engineer
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2009

Commented:
in short:
select max(id) from yourtable where account_id = xxx and id < yyy
Most Valuable Expert 2011
Author of the Year 2014

Commented:
It might make more sense if we could see the CREATE TABLE statements.  I think angelIII has a right answer, but without seeing the important details it's not clear what columns are AUTO_INCREMENT, etc.  Please see http://sscce.org

My guess might be:

SELECT id, account_id FROM myTable WHERE account_id='$id' ORDER BY id DESC LIMIT 2

Then use MySQL_Data_Seek($resource,1)

Author

Commented:
Hi, giving it a try now. The id is auto increment so I'll check that solution. Seems to make sense. max($id) must grab the highest $id available that is less than the supplied.

Author

Commented:
HI, this is the query I'm using. It works but it returns the lowest available id for some reason instead of the next highest below the current id:

$result = mysql_query("SELECT id, MAX(id) FROM contests WHERE account_id = '$account_id' AND id < '$contest_id' ORDER BY id DESC LIMIT 1");

Screenshot of table is attached...

I'm passing $contest_id = 317 and get back 314 (any number I pass gets back 314)
screen.jpg
Guy Hengel [angelIII / a3]Billing Engineer
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2009

Commented:
please remove ORDER BY id DESC LIMIT 1 from the subquery ....
as you use MAX() the LIMIT will "kill" that part.
Billing Engineer
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2009
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
I don't really understand it yet.. but works great.
Thanks!
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.