简体   繁体   English

同一张表上多对多关系的内部联接

[英]Inner Join on many-to-many relationship on the same table

I came across a weird problem while I was trying to apply the Inner Join on the table which has 3 columns -当我尝试在有 3 列的表上应用Inner Join时,我遇到了一个奇怪的问题 -

Table category_subcategory_relationcategory_subcategory_relation

id (PK)
category_id_ref (FK)
subcategory_id_ref (FK)

The columns category_id_ref and subcategory_id_ref are the primary keys of the table category .category_id_refsubcategory_id_ref是表categoryprimary keys

Table categorycategory

id (PK)
category_name (Varchar(200))

I want to Inner Join this two tables and get the columns as following -我想内部加入这两个表并获得如下列 -

Category_Name
Subcategory_Name

I am not able understand how would I be able to get the category_name column from the category table twice, once for the column Category_Name (FK) and again for the column Child_Category_Name (FK) .我无法理解如何从category表中获取category_name列两次,一次用于列Category_Name (FK) ,另一次用于列Child_Category_Name (FK)

You would have to perform two joins, one each on category_id_ref and subcategory_id_ref :您必须执行两个连接,在category_id_refsubcategory_id_ref上各一个:

SELECT a.*, 
       b.category_name AS Category_Name, 
       c.category_name AS Subcategory_Name
FROM category_subcategory_relation a 
JOIN category b 
  ON a.category_id_ref    = b.id
JOIN category c 
  ON a.subcategory_id_ref = c.id

While your category table contains category and subcategory information, you'll have to look at them as two separate tables (one for category and other for subcategory ) to bring this information back to your category_subcategory_relation table.虽然您的category表包含类别和子类别信息,但您必须将它们视为两个单独的表(一个用于category ,另一个用于subcategory )才能将此信息带回您的category_subcategory_relation表。

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

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