Link to home
Start Free TrialLog in
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?
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

in short:
select max(id) from yourtable where account_id = xxx and id < yyy
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)
Avatar of tjyoung
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.
Avatar of 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
please remove ORDER BY id DESC LIMIT 1 from the subquery ....
as you use MAX() the LIMIT will "kill" that part.
ASKER CERTIFIED SOLUTION
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of tjyoung

ASKER

I don't really understand it yet.. but works great.
Thanks!