发现违反对称约束

max*_*max 3 mysql database-design constraint referential-integrity

假设我有一个Friends包含列的表Friend1ID, Friend2ID。我选择用两条记录来代表每段友谊,比如 (John, Jeff) 和 (Jeff, John)。因此,每对朋友应该恰好出现在表中两次。

有时,这个约束被违反,即一对朋友在表中只出现一次。我如何编写一个查询来识别所有这些情况(理想情况下,使用合理的标准 SQL)?换句话说,我希望查询返回此表中的行列表,其中没有对应的行与交换字段。

另一个问题:有没有办法在 MySQL 中强制执行这种参照完整性?

Stu*_*ore 5

要查找行,请使用左外连接:

select 
    a.Friend1ID, a.Friend2ID, b.Friend1ID, b.Friend2ID 
from
    Friends a left join Friends b 
        on (a.Friend1ID=b.Friend2ID and a.Friend2ID=b.Friend1ID)
where 
    b.friend1ID IS NULL ;
Run Code Online (Sandbox Code Playgroud)