Paweł Skaba
Paweł Skaba

Reputation: 681

PHP + mysql - left join - three tables

I've got a weird question. I have three tables: - table_a with columns (id, product_id, customer_id, location, phone) - table_b with columns (id, product_id, product_name) - table_c with columns (id, customer_id, customer_name)

What I would like to display is a table with following content: table_a.id, product_name, customer_name, location, phone

So I assume somehow I should use left join table_b, table_c with table_a.

I've tried multiple approaches like:

SELECT*FROM table_a INNER JOIN table_b, table_c
ON table_a.product_id = table_b.product_id
ON table_a.customer_id = table_c.customer_id

I want to avoid making duplicates of product_id/customer_id in final table..

Upvotes: 0

Views: 1819

Answers (3)

Indrasis Datta
Indrasis Datta

Reputation: 8618

You can get all the other fields, but which id are you trying to get? All 3 tables have id field.

Assuming you can take the id of first table:

SELECT table_a.id, table_b.product_name as product_name, table_c.customer_name as customer_name, table_a.location as location, table_a.phone as phone

FROM table_a INNER JOIN table_b

ON table_a.product_id = table_b.product_id

INNER JOIN table_c

ON table_a.customer_id = table_c.customer_id

Hope this helps.

Peace! xD

Upvotes: 1

haakym
haakym

Reputation: 12358

It can help to specify the table name prior to the table attribute in your select statement. Hope this helps!

select
    table_a.id,
    table_b.product_name,
    table_c.customer_name,
    table_a.location,
    table_a.phone
from table_a
left join table_b
    on table_a.product_id = table_b.product_id
left join table_c
    on table_a.customer_id = table_c.customer_id

Upvotes: 2

Tuan Duong
Tuan Duong

Reputation: 515

You need to join sequently table_a with table_b to get product_name, then table_a with table_c to get customer_name. You can try with this:

SELECT table_a.id, product_name, customer_name, location, phone
FROM table_a 
    INNER JOIN table_b ON table_a.product_id = table_b.product_id
    INNER JOIN table_c ON table_a.customer_id = table_c.customer_id

Upvotes: 2

Related Questions