加入4个表相关

时间:2013-10-07 22:18:35

标签: mysql sql

我正在尝试加入这4个表:

客户:

  • id_customer;
  • 名;

雇主:

  • id_employer;
  • id_customer;

products_to_employer

  • id_product;
  • id_employer;

产品

  • id_product;
  • name_product;
  • 码;
  • 价格;

我基本上试图获得客户的所有产品。基本上每个产品都与id_employer相关联,但每个雇主都与客户有关,所以我想要的是将所有与雇主无关的产品带到雇主的“父母”那里。

我想得到的结果是:

结果:

示例:变量$ id_customer:4

产品结果:

  • id_customer(id nr 4)
  • name_product;
  • name_product;
  • 码;
  • 价格;

2 个答案:

答案 0 :(得分:1)

这是要求:

  

我基本上试图获得客户的所有产品

因此,只需在where上为过滤器应用一些连接和id_customer子句

select p.* from products p
join products_to_employer pe on p.id_product = pe.id_product
join employers e on pe.id_employer = e.id_employer
join customers c on e.id_customer = c.id_customer
where c.id_customer = 4

注意:由于您已经过滤了结果,因此不需要将id_customer添加到结果中。

答案 1 :(得分:0)

select c.id_customer, c.name, p.name_product, p.code, p.price
from products p
    inner join products_to_employer pte on (pte.id_product = p.id_product)
    inner join employers e on (e.id_employer = pte.id_employer)
    inner join customers c on (c.id_customer = e.id_customer)
where c.id_customer = 4