‘Discussions’ table schema
title description desid replyto upvote downvote views
browser used a1 none 1 1 12
- bad topic b2 a1 2 3 14
sql database a3 none 4 5 34
- crome b4 a3 3 4 12
The above table has two types of content types Main Topics and Comments. Unique content identifier ‘desid’ used to identify that its a main topic or a comment. ‘desid’ starts with ‘a’ for Main Topic and for comment ‘desid’ starts with ‘b’. For comment ‘replyto’ is the ‘desid’ of main topic to which this comment is associated.
I like to find out the list of the top main topics that are arranged on the basis of (upvote+downvote+visits+number of comments to it) addition. The following query gives top topics list in order of (upvote+downvote+visits)
select * with highest number of upvote+downvote+views by query
select *
from [DB_user1212].[dbo].[discussions]
where desid like 'a%'
order by (upvote+downvote+visited) desc
For (comments+upvote+downvote+views ) i tried
select *
from [DB_user1212].[dbo].[discussions]
where desid like 'a%'
order by (select count(*)
from [DB_user1212].[dbo].[discussions]
where replyto = desid )+upvote+downvote+visited) desc
but it didn’t work . Because its not possible to send desid from outer query to innner subquery. Please tell me how to solve this. Please note that I want solution in query language only.
You need to use table aliases:
Now, in the subquery, you can refer to the outer tables by alias (here,
d1). I also addedd2, which is not necessary here, but it can be useful to be explicit in subqueries.