PHP + mysql - 左连接 - 三个表

时间:2016-03-16 17:38:47

标签: php mysql left-join

我有一个奇怪的问题。我有三张桌子: - 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)

我想要显示的是包含以下内容的表格: table_a.id,product_name,customer_name,location,phone

所以我假设我应该使用左连接table_b,table_c和table_a。

我尝试了多种方法,例如:

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

我想避免在决赛桌中复制product_id / customer_id。

3 个答案:

答案 0 :(得分:2)

您需要将table_a与table_b连接以获取product_name,然后将table_a与table_c连接以获取customer_name。你可以试试这个:

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

答案 1 :(得分:2)

可以帮助在select语句中的table属性之前指定表名。希望这有帮助!

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

答案 2 :(得分:1)

你可以获得所有其他字段,但是你想要获得哪个ID?所有3个表都有id字段。

假设您可以获取第一张表的ID:

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

希望这有帮助。

和平!的xD