简体   繁体   中英

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM