Jump to content

Last_insert_id


ceci

Recommended Posts

hi.

 

i have two tables tableA and tableB in a 1-many relationship.  I need the last_id from tableB.

 

I tried this but it returns all the items.

SELECT last_insert_id(item_id) as 'lastID', a.book_id, a.title  FROM tableA a LEFT JOIN tableB b on a.item_id = b.fk_item_id ORDER BY item_id DESC 

And if I use Limit 1, you guest it, it only returns one.

 

It should return 1 for each item on tableA.

 

How do I do this? Thank you.

 

Ceci

Link to comment
https://forums.phpfreaks.com/topic/201440-last_insert_id/
Share on other sites

last_insert_id() only returns the last id after an INSERT (and in some cases for an UPDATE) query has been preformed using the same database connection.

 

The way you are using it causes it to return the item_id value.

 

What exactly are you trying to accomplish?

Link to comment
https://forums.phpfreaks.com/topic/201440-last_insert_id/#findComment-1056871
Share on other sites

sorry i was not clear the first time around.

 

I am looking for the latest item entered from the second table (tableB) using Left Join.

 

so if tableA has 2 items

ID  itemType

1  shirts

2  pants

 

 

and tableB has 2 orders for ID 1(shirts); 3 items for ID 2 (pants)

 

id fk_item_id    Orders

1  1                  red-shirt

2  1                  white-shirt        /* last_inster_id  */

3  2                  small-size

4  2                  large-size

5  2                  medium-size    /* last_insert_id for item ID2 */

 

I am interested in the last item ordered from tableB.  HOw do I get that?

 

In other words I want to do this but in one shot:

 

// First Query

$qryResultA = mysql_query("SELECT id, item_id FROM tableA");

While($row = mysql_fetch_array($qryResultA){

      // Second Query to get the last item.

      $getItemsFromTableB = mysql_query("SELECT *, id FROM tableB WHERE fk_item_id = '$row['item_id']' ORDER BY id DESC ")

      $innerRow = mysql_fetch_array($getItemsFromTableB);

}

 

Link to comment
https://forums.phpfreaks.com/topic/201440-last_insert_id/#findComment-1056888
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.