PHP + mysql - 左连接 - 三张表

PHP + mysql - left join - three tables

我有一个奇怪的问题。我有三个 table: - table_a 包含列(id、product_id、customer_id、位置、phone) - table_b 列 (id, product_id, product_name) - table_c 列 (id, customer_id, customer_name)

我想显示的是一个table,内容如下: table_a.id、product_name、customer_name、位置、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

我想避免在最终 table..

中复制 product_id/customer_id

您需要依次加入 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

你可以获取所有其他字段,但你想获取哪个id?所有 3 table 都有 id 字段。

假设你可以取第一个table的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

在 select 语句中的 table 属性之前指定 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