Jump to content

Bad results when joining 3 tables


tHud

Recommended Posts

Hi :)

 

I am trying to join 3 tables. I think I know why I am getting bad results, but I don't know how to rectify the issue.

 

Here are the tables...

 

Companies

comp_id

comp_name

 

Orders

ord_id

comp_id

ord_number

 

Invoices

inv_id

comp_id

inv_number

 

 

I would like to have a table that displays...

 

comp_name -- ord_number -- inv_number

 

I am using comp_id as the common factor, but when I try...

companies.comp_id = orders.ord_id and companies.comp_id = invoices.inv_id

 

I get 'odd' results. I think I see why the results are bad, but don't know what to do about it.

 

Any thoughts on what to do please?

 

Thank you :)

 

 

Link to comment
Share on other sites

You need to join them on the common keys. For example:

SELECT a.comp_name,b.ord_number,c.inv_number FROM Companies AS a
LEFT JOIN Orders AS b ON b.comp_id=a.comp_id
LEFT JOIN Invoices AS c ON c.comp_id=a.comp_id

 

However, if I am understanding what you are trying to do, you might change your table structures so that the invoice references the order number:

 

 

Companies

comp_id

comp_name

 

Orders

ord_id

comp_id

ord_number

 

Invoices

inv_id

ord_id

inv_number

 

In this case, your query would look like this:

SELECT a.comp_name,b.ord_number,c.inv_number FROM Companies AS a
LEFT JOIN Orders AS b ON b.comp_id=a.comp_id
LEFT JOIN Invoices AS c ON c.ord_id=b.ord_id

 

 

 

 

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.