Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.