Jump to content

JOIN Query for 2 Tables - Cannot get a valid result w/out Error


OldWest

Recommended Posts

I've got two tables.

 

I am trying to JOIN both tables by product_id (both tables contain this field), and WHERE status equals A in table1.

 

Here is what I have so far with absolutely no luck!

 

$query = "SELECT product_id FROM products, product_descriptions WHERE products.status='A'";

 

From what I understand, I am  SELECTing product_id from both tables (I also confirmed this much of the statement is working). FROM 2 tables as noted: products, product_descriptions. WHERE products status field equals value A...

 

Obviously my query is screwed. I've spent some hours on dev.mysql.com and have not been able to piece this together properly..

 

Thanks for any advice.

 

Does anyone know why this is not working as expected?

Link to comment
Share on other sites

You have to JOIN the two tables on a common field. Otherwise, you will get a Cartesian product (every one in each table matched with every row in the other table(s))

 

$query = "SELECT product_id 
FROM products JOIN product_descriptions ON products.product_id = product_descriptions.product_id
WHERE products.status='A'";

Link to comment
Share on other sites

Thank you for that tip.. I was so darn close! The query you sent would not work on my version of mysql ..

 

SELECT product_id 

was required to be

SELECT product_descriptions.product_id 

 

But it appears to be working now with that small tweak. Thank you for your advice.

 

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.