I'm trying to make a simple forum for a school-project.
I'm having some troubles with my query.
I have 3 tables, that I'm trying to join. "Categories", "Threads" and "Post".
ERD
The table data
Category
Threads
Posts
(Even though the name-spelling is a little bit different in the DB, the columns and tables are the same, as shown in the image.)
As soon as I join the second table ("Posts"), the result from the "Threads"-count is wrong.
If I only left join and count the rows in "Threads", then the result is right.
When i do this:
SELECT Category.Name AS CategoryName, Category.Description AS
CategoryDescription, COUNT(Threads.Id) AS NumberOfThreads
FROM Category
LEFT JOIN Threads ON Threads.FkCategoryId = Category.Id GROUP
BY Category.Name, Category.Description
The Result is
Which returns the actual number of rows in "Threads". All is good so far,
BUT when i add the second join
SELECT Category.Name AS CategoryName, Category.Description AS CategoryDescription,
COUNT(Threads.Id) AS NumberOfThreads,
COUNT(Posts.Id) AS NumberOfPosts
FROM Category
LEFT JOIN Threads ON Threads.FkCategoryId = Category.Id
LEFT JOIN Posts ON Posts.FkThreadId = Threads.Id
GROUP BY Category.Name, Category.Description
Then i get this result:
Which shows the actual number of rows in "Posts" as both "Threads" and "Posts".
I have also tried to combine multiple queries in one like this:
SELECT Category.Name AS CategoryName, Category.[Description] AS
CategoryDescription, COUNT(Threads.Id) AS NumberOfThreads
FROM Category
LEFT JOIN Threads ON Category.Id = Threads.FkCategoryId
GROUP BY Category.Name, Category.Description;
SELECT COUNT(Posts.Id) AS NumberOfPosts
FROM Category
LEFT JOIN Threads ON Category.Id = Threads.FkCategoryId
LEFT JOIN Posts ON Threads.Id = Posts.FkThreadId
GROUP BY Category.Id;
Which gives me this result:
which is the correct data. I would just rather combine it in 1 query, because I can't "Eval" "NumberOfPosts" form the second query.
I get this Error:
"DataBinding: 'System.Data.DataRowView' does not contain a property
with the name 'NumberOfPosts'"
I have read and tried a lot of different things, and don't know how to solve it. I hope someone can help.