Avatar of tjyoung
tjyoung
 asked on

How to get the id that came BEFORE the provided id

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?
PHPMySQL Server

Avatar of undefined
Last Comment
tjyoung

8/22/2022 - Mon
Guy Hengel [angelIII / a3]

in short:
select max(id) from yourtable where account_id = xxx and id < yyy
Ray Paseur

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)
tjyoung

ASKER
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.
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
tjyoung

ASKER
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]

please remove ORDER BY id DESC LIMIT 1 from the subquery ....
as you use MAX() the LIMIT will "kill" that part.
ASKER CERTIFIED SOLUTION
Guy Hengel [angelIII / a3]

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
tjyoung

ASKER
I don't really understand it yet.. but works great.
Thanks!
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.