简体   繁体   中英

Correct way to join tables using a single table and a relationship table

I am totally confused here... I have a table that lists parts. All parts are listed in the same table. The parts have a relationship with each other. Some parts are contained by other parts:

Key Desc          Exists
--- ------------- -------
5   Assy            1
6   Component A     1
7   Component B     0

In the table above Component B does not exist in real life.

The three parts go together like so:

Assy
   -Component 1 Exists
   -Component 2 Does not exist

I have a table that calls out relationships like so:

ParentKey   Child Key
----------  -------------
5              6
5              7

I need to find all parents that have a child that do not exist.

I have done simple selects in the past but this is hurting my brain. Everything I try here does not get anywhere close.

Can someone please point me in the right direction?

Try this:

SELECT * 
       FROM part as p
       INNER JOIN partRelationships as pr on p.Key = pr.ParentKey
WHERE p.ChildKey IN (
                      SELECT Key FROM part WHERE Exists = 0
                    )

Is this what you are looking for? Or are the Assemblies recursive (ie, Assembly-->has Parts--> which have Parts --> ...)?

DROP TABLE IF EXISTS Parts;
DROP TABLE IF EXISTS [assemblies];
GO
CREATE TABLE Parts 
(
    [Key] INT
    , [Desc] VARCHAR(500)
    , [Exists] BIT
);
GO

INSERT Parts ([Key],[Desc],[Exists]) VALUES
    (5, 'Assy', 1)
    , (6, 'Component A', 1)
    , (7, 'Component B', 0)
    ;

GO
CREATE TABLE [Assemblies]
(
    ParentKey INT
    , ChildKey INT
);
GO
INSERT [Assemblies] (ParentKey, ChildKey) VALUES
    (5, 6)
    , (5, 7);

GO

SELECT 
    parent.[Key]
    , parent.[Desc] AS AssemblyName
    , child.[Desc] AS PartName
    , child.[Exists]
FROM
    [Assemblies] a
    INNER JOIN dbo.Parts parent
        ON parent.[Key] = a.[ParentKey]
    INNER JOIN dbo.Parts child
        ON child.[Key] = a.[ChildKey]
WHERE
    child.[Exists] = 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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