简体   繁体   English

MySQL View外键可以为NULL

[英]MySQL View where foreign key can be NULL

I would like to know how to create view which also works even if the foreign key is NULL . 我想知道如何创建即使外键为NULL的视图也可以使用。 For example we have table Person which has a primary key and two foreign keys: 例如,我们有一个表Person ,它有一个主键和两个外键:

  • IdPerson IdPerson
  • FkName
  • FkSurname 姓氏

Both foreign keys can be NULL . 两个外键都可以为NULL Now we also have two tables, table Name : 现在我们还有两个表,表

  • IdName ID名称
  • Name 名称

And table Surname : 和表

  • IdSurname 姓氏
  • Surname

Now we create view to display name and surname for each Person: 现在,我们创建视图以显示每个人的姓名和姓氏:

CREATE VIEW `Database`.`ViewPerson` AS 
SELECT `N`.`Name`, `S`.`Surname`
FROM `Person` `P`, `Name` `N`, `Surname` `S`
WHERE (`P`.`FkName` = `N`.`IdName`) AND (`P`.`FkSurname` = `S`.`IdSurname`)

The problem is, if the foreign key FkSurname is NULL, than that row will not be displayed even though FkName is defined. 问题是,如果外键FkSurname为NULL,则即使定义了FkName,也不会显示该行。 I want that even if both foreign keys are NULL it still returns row where both columns are NULL. 我希望即使两个外键都为NULL,它仍然返回两列均为NULL的行。 Now I know that I could solve it by adding in table Name and in table Surname row, that has NULL under Name/Surname and then in the FkName and FkSurname reference a row that has NULL values under those two columns. 现在,我知道可以通过在表名称和表姓氏行中添加在名称/姓氏下具有NULL的表,然后在FkName和FkSurname引用中在这两列下具有NULL值的行来解决该问题。 But I would still like to find out if there is a solution where foreign key is NULL and the row is returned. 但是我仍然想找出是否存在外键为NULL并返回该行的解决方案。

If I understand your question correctly, you want to get the corresponding values (even if null) for the Name and Surname fields in the Name and Surname table for each record in the Person table. 如果我正确理解了您的问题,则希望为“人”表中的每个记录获取“名称”和“姓氏”表中“名称”和“姓氏”字段的相应值(即使为null)。

This seems like a straightforward case where LEFT JOIN would work correctly. 这似乎是一个简单的案例,其中LEFT JOIN将正常工作。 So, based on your query above, the SQL would be: 因此,根据您上面的查询,SQL将为:

CREATE VIEW Database.ViewPerson AS
SELECT
  N.Name, S.Surname
FROM Person P
  LEFT JOIN Name N ON N.IdName = P.FkName
  LEFT JOIN Surname S ON N.IdSurname = S.FkSurname;

(sorry of the syntax isn't 100% correct, I didn't go through and create a test table to confirm it) (抱歉,语法不是100%正确,我没有通过创建测试表来确认它)

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

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