简体   繁体   English

从同一个多对多表查询

[英]Query from the same many-to-many table

I need to maintain a material table.我需要维护一个材料表。 Each material may has one or more alternative materials, so it would form a many-to-many relationship on the same table.每种材料可能有一种或多种替代材料,因此它会在同一张桌子上形成多对多关系。 Users can query the alternatives by a given material's part number.用户可以通过给定材料的零件号查询替代品。

I created two tables,as follows.我创建了两个表,如下所示。

CREATE TABLE material (
    id int(3) NOT NULL PRIMARY KEY AUTO_INCREMENT,
    pn varchar(20) NOT NULL UNIQUE
);
CREATE TABLE mapping (
    pn_id int(3) NOT NULL,
    main_pn_id int(3) NOT NULL,
    PRIMARY KEY (pn_id, main_pn_id)
);
ALTER TABLE mapping ADD FOREIGN KEY (pn_id) REFERENCES material (id);
ALTER TABLE mapping ADD FOREIGN KEY (main_pn_id) REFERENCES material (id);

My querying inputs are always pn (part number of a material).我的查询输入始终是 pn(材料的零件编号)。 It means the select command would look like this.这意味着选择命令看起来像这样。

SELECT * FROM material ..... WHERE pn="XXXXX";

If I'd like to find the alternatives for a given material.如果我想找到给定材料的替代品。 I need to query its id by part number first.我需要先通过零件号查询它的 id。 Then I use id to find pn_id by然后我使用 id 来查找 pn_id

SELECT pn_id FROM mapping WHERE main_pn_id=$id

At last, using pn_id to find pn from material table.最后,使用 pn_id 从材料表中查找 pn。

I knew it can be achieved by subquery or UNION to get alternatives for a material, but using subquery and UNION may influence the querying performance.我知道可以通过子查询或 UNION 来获取材料的替代品,但是使用子查询和 UNION 可能会影响查询性能。 My system may be used by hundreds of people.我的系统可能会被数百人使用。

I tried to use JOIN to complete a querying, but I still could not figure out how to use JOIN to query alternatives in my situation.我尝试使用 JOIN 来完成查询,但我仍然无法弄清楚如何使用 JOIN 来查询我的情况。 Could anyone kindly help me on this?任何人都可以帮助我吗? Thanks.谢谢。

Why not a simple join to Material twice.为什么不简单地连接到 Material 两次。

Note I used left joins here as I'm unsure if all materials would be in the mapping table.注意我在这里使用了左连接,因为我不确定所有材料是否都在映射表中。

SELECT M1.ID as MainPartID
     , M1.PN as MainPartNumber
     , M2.ID as AltPartID
     , M2.PN as AltPartNum
FROM material M1
LEFT JOIN Mapping Map
 on M1.ID = MAP.PN_ID
LEFT JOIN Material M2
 on M2.ID = MAP.Main_PN_ID
WHERE M1.PN = 'XXXXX'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM