要求:我想知道每個人張貼了多少張圖片。COUNT()在特定列上返回0
因此,我創建一個表格架構如下。
Table=Person
==========
Id (PK) , Column1, Column2, LId (FK)
Table=ListMaster
============
Id (PK) , LId (Unique)
Table = ListDetail
===========
Id (PK), LId(FK), DataId(FK)
Table = Image
=========
Id (PK), Column1, Column2
和使用查詢SQL
SELECT Person.Id AS PersonId,
Person.Column1 AS PersonC1,
Person.Column2 AS PersonC2,
COUNT(Image.Id) AS ImageCount
FROM Person
LEFT OUTER JOIN ListMaster ON Person.LId = ListMaster.LId
LEFT OUTER JOIN ListDetail ON ListDetail.LId = ListMaster.LId
LEFT OUTER JOIN Data AS Image ON ListDetail.DataId = Image.Id
GROUP BY Person.Id,
Person.Column1,
Person.Column2
我注意到有些人的「ImageCount」有「0」雖然有他以前張貼的圖片。
能否請你告訴我如何解決我的問題或告訴我,甚至在邏輯上可以做我想做的事情?我懷疑我的桌子設計有誤。
Sample Data
=======
Table = Person
Id (PK)(bigint identity) | Column1 (nvarchar(max)) | Column2 (nvarchar(max)) | LId (FK) (bigint [null])
1 | Test 1 C1 | Test1 C2 | 1
2 | Test 2 C1 | Test 2 C2 | 2
3 | Test 3 C1 | Test 3 C2 | NULL
4 | Test 4 C1 | Test 4 C4 | 37
Table = ListMaster
Id (PK)(bigint)(identity) | LId (Unique)(bigint)
1 | 1
2 | 2
3 | 37
Table = ListDetail
Id (PK)(bigint identity)| LId(FK)(bigint not null)| DataId(FK)(bigint not null)
1 | 1 | 1
2 | 1 | 2
3 | 2 | 3
4 | 37 | 4
Table = Image
Id (PK)(big int not null)(identity) | Column1 (nvarchar(max)) | Column2 (nvarchar(max))
1 | Location 1 | Dummy Data 1
2 | Location 2 | Dummy Data 2
3 | Location 3 | Dummy Data 3
4 | Location 4 | Dummy Data 4
我希望COUNT(Image.Id)AS ImageCount應該返回
2
1
0
1
但它返回
2
1
0
0
編輯1:更改表的設計
EDIT 2 :添加樣本數據
'MyTable.LId' ?? –
你的查詢看起來好,所以可能是數據問題。嘗試刪除'COUNT()'和'GROUP BY'並添加'DATA。*',以便在分組之前查看您的數據結果。 –
@JuanCarlosOropeza我已經嘗試了SELECT * FROM Image,它顯示了正確的數據。但是當我嘗試使用COUNT()和GROUP BY時,「ImageCount」變爲「0」。 –