[英]PHP + mysql - left join - three tables
我有一个奇怪的问题。 我有三个表:-具有列(id,product_id,customer_id,位置,电话)的table_a-具有列(id,product_id,product_name)的table_b-具有列(id,customer_id,customer_name)的table_c
我要显示的是一个具有以下内容的表:table_a.id,product_name,customer_name,位置,电话
因此,我假设我应该以某种方式将左连接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。
您需要随后将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
在select语句中,可以在表属性之前指定表名称。 希望这可以帮助!
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
您可以获取所有其他字段,但是您要获取哪个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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.