SQL Server中表之间的参照完整性

时间:2019-07-16 13:10:30

标签: sql sql-server

enter image description here

我有2个表,MembersEnrollments。可以使用主键Member ID连接两个表。

我需要编写一个查询,该查询返回Members表中的所有成员,而这些成员在Enrollments表中没有对应的行,反之亦然。

这是我到目前为止所拥有的:

IF OBJECT_ID('tempdb..#memberswithoutenrollments') IS NOT NULL
    DROP TABLE #memberswithoutenrollments 

SELECT m.* 
INTO #memberswithoutenrollments 
FROM ABC_Members m 
LEFT OUTER JOIN ABC_MemEnrollment e ON m.MemberID = MemberID

2 个答案:

答案 0 :(得分:1)

FULL JOIN是比较两个表之间的列表的一种简单方法:

SELECT COALESCE(e.MemberID, m.MemberID),
       (CASE WHEN e.MemberID IS NULL THEN 'No Enrollments' ELSE 'No Member' END)
FROM ABC_Members m FULL JOIN
     ABC_MemEnrollment e
     ON m.MemberID = e.MemberID
WHERE e.MemberID IS NULL OR m.MemberID IS NULL;

但是,如果您具有适当的外键关系,那么永远不要有没有成员的注册。

答案 1 :(得分:0)

您可以在这里使用NOT IN来获得好处。

WITH
    -- Create a list of all of the matches
    in_table AS
        (
            SELECT
                Member_ID
            FROM
                Enrollments
            WHERE
                Members.MemberID = Enrollments.Member_ID
        ),

    result_table AS
        (
            SELECT
                *

            FROM
                Members

            -- Grab only the values from members that DO NOT APPEAR in in_table
            WHERE
                MemberID NOT IN (SELECT DISTINCT FROM in_table)
        )

-- Grab all results
SELECT * FROM result_table