Jump to content

Pulling data from 2 separate tables


codeline

Recommended Posts

I've got a table (tbl_items) that holds a number of items and the individual information for each. Within 'tbl_items' I also have a row labeled 'category_id' in which each item is given a number (ex: 2).

 

I've got a separate table (tbl_items_categories) that only has 2 rows: 'category_id' and 'category_name'.

 

I wasn't sure if a JOIN method would be best for this but what would be the best approach to list all items and within each item, also echo out the name of the category they belong to and not the category_id number?

Link to comment
Share on other sites

I was curious, can you also use a JOIN when the fields do not have the same name? For instance, maybe within 'tbl_items' the field was labeled "category_id" but within 'tbl_items_categories' the field was just 'id'?

 

Yes, absolutely you can. But, by using the same name for foreign keys does simplfy things and makes debugging much easier. BUt if the field names were different, this is one way to join the tables

SELECT *
FROM tbl_items
JOIN tbl_items_categories ON tbl_items.category_id = tbl_items_categories.id

 

By the way, I used '*' in my examples above, but I am of the opinioin you should always explicitly include the field names in the SELECT statemetn for the data you want.Using '*' increawses overhead on the server and can lead to potential problems - especially when joining tables

Link to comment
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.