views:

78

answers:

3

Apologies - am not good at SQL. Perhaps this is a simple query - I don't know.

What I have is a basic forum table - e.g.

id poster title type content postedon parentID

in this scheme, if a user asks a question, it is type = 0, and if it is an answer, type = 1. If the entry is an answer, I update the parentID to the id on the question row.

All I want to do is pull the questions in a SQL query, along with a number that has the total number of answers to the question - for e.g. a result row would look like

[email protected] "how do I do this?" 4

Where (4) would be the total answers to my question. I want to do this in a single query - without having to pull the questions first, and then run repeated queries for each question Id to find the count of the answers.

How do I do this?

Thank you all,

(PS - is there a way to do the query in Linq expressions? I would do that instead of a stored procedure if I could)

+3  A: 
select ft1.poster, ft1.title, count(ft2.id)
    from ForumTable ft1
        left join ForumTable ft2
            on ft1.id = ft2.parentID
                and ft2.type = 1
    where ft1.type = 0
    group by ft1.poster, ft1.title
Joe Stefanelli
Joe - that seems to (almost) do it. But it returns only rows where the question had 1 or more answers, but not those that have none (0 answers)...what do I modify?
jeremy
@joe - tried that, and I get a '1' for all the questions that had no answers... (the parentID column is filled with 0 for all questions)
jeremy
Yeah, realized my mistake too. You want to left join and count from the second table. See edited answer.
Joe Stefanelli
Yes, that's exactly what I wanted. Thank you very much. And sorry I can't 'vote you up', still a student on Stackoverflow, you see!
jeremy
A: 

Can you try this and see if it meets your needs?

SELECT poster, title, ISNULL(X.NoOfAnswers,0)
FROM forum LEFT OUTER JOIN
(SELECT parentId, COUNT(id) as NoOfAnswers
FROM forum
GROUP BY parentId) X
ON forum.id = X.parentId
WHERE forum.type = 0
InSane
yes, this works too. Thanks.
jeremy
A: 

select A.poster,a.acontent,count(B.parentId) as Answers from forum B, forum A where B.atype=1 and B.parentId=A.id group by a.id,a.poster,a.acontent

enthu