我们有两张表,一张有 id,一张有名字。某些 id 不是必需的(可以为空),例如:
rowId item1Id, item2Id, item3Id (item3Id can be null)
在我们加入这两个表之后,我们得到了 id 和名称。但如果 item3 Id 为 null,则不显示该行。
一些数据:
表格1
rowId, item1Id, item2Id, item3Id
1、2、3、4
2、1、5、空
在我们的例子中,我们得到一行(1 行)
因此,如果它为空,则它在 Table2 中不存在并且该行未显示,但我们希望显示空。因此,当我们离开连接这两个表时,结果应该有 2 行。
这是 sql :
SELECT Recipes.recipeId, Recipes.userId,Users.firstName + ' ' + Users.lastName as userName, servingTypeId,
Codings.coding as servingType, categoryId, Codings_2.coding as healthAspects, continentId,
Codings_3.coding as continent, countryId, CodingsAssociated.coding as country, typeOfPreparationId,
Codings_4.coding as typeOfPreparation, flavourId, Codings_5.coding as flavour, preparationSkillId,
Codings_6.coding as preparationSkill, seasonId, activePreparationTime,
overallPreparationTime, isLocalDelight, servings, Codings_7.coding as season ,
calories, youTubeId, datePosted, isComposite, Recipes.isApproved, Recipes.timestamp, title,
localDelightRegion, otherFeatures, cookingInstructions
FROM Recipes LEFT OUTER JOIN
Codings ON Recipes.servingTypeId = Codings.codingKeyId LEFT OUTER JOIN
Codings as Codings_2 ON Recipes.categoryId = Codings_2.codingKeyId LEFT OUTER JOIN
Codings as Codings_3 ON Recipes.continentId = Codings_3.codingKeyId LEFT OUTER JOIN
CodingsAssociated ON Recipes.countryId = CodingsAssociated.codingKeyId LEFT OUTER JOIN
Codings as Codings_4 ON Recipes.typeOfPreparationId = Codings_4.codingKeyId LEFT OUTER JOIN
Codings as Codings_5 ON Recipes.flavourId = Codings_5.codingKeyId LEFT OUTER JOIN
Codings as Codings_6 ON Recipes.preparationSkillId = Codings_6.codingKeyId LEFT OUTER JOIN
Codings as Codings_7 ON Recipes.seasonId = Codings_7.codingKeyId LEFT OUTER JOIN
RecipesTranslations ON Recipes.recipeId = RecipesTranslations.recipeId LEFT OUTER JOIN
Users ON Recipes.userId = Users.userId
WHERE CodingsAssociated.languageId = @languageId AND Codings.languageId = @languageId
AND Codings_2.languageId = @languageId AND Codings_3.languageId = @languageId
AND Codings_4.languageId = @languageId AND
Codings_5.languageId = @languageId AND Codings_6.languageId = @languageId AND RecipesTranslations.languageId = @languageId
AND Codings_7.languageId = @languageId
例如,因为 seasonId 有时为空,所以不会显示 Codings_7.coding 的连接,但我也不会显示 ID 为空且名称也为空的这些行。