tags:

views:

28

answers:

2

Please see screenshot:

screenshot

Goal:

  • id like to have comments nested 1 level deep
  • The comments would be arranged so that rating of the parent is in descending order
  • the rating of the children comments is irrelevant

The left hand side of the screenshot shows the output that Id like. The RHS shows the table data. All of the comments are held in 1 table.

Im a beginner with SQL queries, the best I can do is:

SELECT * 
FROM [Comments] 
WHERE ([ArticleId] = @ArticleId) ORDER BY [ThreadId] DESC, [DateMade] 

This somewhat does the job, but it obviously neglects the rating. So the above statement would show output where Bobs Comment and all of the children comments are before Amy's and her childrens comments. How can I run this query correctly?

A: 

I would think something like this might come close.

SELECT child.* FROM Comments parent, Comments child WHERE parent.id = child.parent_id ORDER BY parent.rating DESC, DateMade DESC

This is going to have weird results if the rating of 2 threads is the same, so you'll have to order on that too somehow.

Peter Tillemans
A: 
SELECT c.* 
FROM Comments AS c
JOIN Comments AS tr ON tr.threadID = c.threadID 
 AND tr.ArticleId = c.ArticleId AND tr.isParent = 1
WHERE (c.ArticleId = @ArticleId) 
ORDER BY tr.Rating DESC, c.ThreadId DESC, c.DateMade 

You have to join the table with itself to get the parents rating then you sort by the thread rating first, then by thread id in case many threads have the same rating, and then by comment date.

You dont have to shove int sorting by c.isParent DESC before date cause this is the oldest comment in the thread.

Imre L
thanks, I spent the whole day yesterday trying to get something to work. I spent alot of time looking into case statments to no avail. I didnt even consider joining a table to itself, thanks for this insight.Clarifying question to anyone who's reading. 1) Would I have been better off if I put parent and children in seperate tables? 2) Is the above query considered "expensive" or is that the typical type of query one needs to have when dealing with the initial requirements, just trying to learn more, thanks
citrus
1) I think no. What comes into my mind is storing an additional field "threaRating" to prevent the join at all with the expense of having to update 1+n comments on thread rating change. 2) since it is 1:1 join it should not be costly as long as you have indexes set correctly to allow fast lookup.
Imre L