SQL多对多查询问

时间:2018-08-08 06:44:31

标签: java mysql sql many-to-many

产品

id_product 产品名称 componentID

组件

componentdID nameofComponent

我在这里有一份将在Combobox中使用的产品的列表,在右边,当我选择一个产品时,我需要的就是Jtable,其中列出了制造该产品所需的所有组件。我如何在selectProduct中进行SQL查询。 还要提及的是,一个产品最多可以包含100个组件。至少有50种产品

谢谢

1 个答案:

答案 0 :(得分:0)

并且您应该避免直接在产品表中的componetId上使用,以避免产品的无用复制来维护与组件的关系

为此 您可以创建一个特定的表来维护产品和组件之间的关系,例如:

 table product_component ( id, product_id, componentdID  ) 

然后您可以选择产品的组成部分作为

 select a.productName, b.nameofComponent 
 from product_component  c 
 inner join product a on a.product_id = c.product_id
 inner join  component b on b.componentdID   = c.componentdID   

以及特定产品

 select a.productName, b.nameofComponent 
 from product_component  c 
 inner join product a on a.product_id = c.product_id
 inner join  component b on b.componentdID   = c.componentdID 
 where a.product_id = your_product_id_value