我們有兩個表格,一個帶有ids和一個帶有名稱。有些ID是不需要(可以爲空),例如:內部加入null 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,NULL
在我們的案例中,我們得到一行結果(1行)
所以,如果它是空的,它不存在於表2中,並且行未顯示,但我們想要顯示空值。 所以當我們離開連接這兩個表時,結果應該有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是空的名字也是空的。
你的問題是什麼? – xdazz
左連接將做你想要的。但是,如果你過濾table2列上的表格,你將有效地恢復到內部連接。所有這些過濾器都應該移至ON子句。 –
很難說這裏有什麼問題,但我想你需要做一個外連接,並且從tsql標記我猜你使用MS SQL服務器,所以在這裏你去:http://msdn.microsoft。 com/en-us/library/aa213228(v = sql.80).aspx – bpgergo