Domanda

I have two tables, likes and comments both of which refer to topic posts - like a topic of a forum for example.

Both of them have a column that refers to a specific topic_id.

Now here's the deal: i want to create a top 5 chart of most liked + commented, the total of both summed up i mean, topics.

For example i did this query for selecting from the topics table the most liked, i want to make the same chart with the total of likes + comments. Here's my top 5 topics by total of likes only.

SELECT topics.* ,
COUNT(q_id)
AS post_count 
FROM topics 
LEFT JOIN likes 
ON topics.id = likes.q_id 
WHERE topics.to_user = 'someuser' 
GROUP BY likes.q_id  
ORDER BY post_count DESC 
LIMIT 0, 5

Tnx in advance!

È stato utile?

Soluzione 4

SELECT posts.id, count(comments.id) + count(likes.id) AS score 
FROM posts
LEFT JOIN comments ON posts.id = comments.post_id 
LEFT JOIN likes ON posts.id = likes.post_id 
GROUP BY posts.id 
ORDER BY score desc;

For those interested here's the solution.

Altri suggerimenti

This will works like a charm!!

      SELECT topics.id
            ,count(DISTINCT(comments.id)) + count(DISTINCT(likes.id)) AS score 
      FROM topics
      LEFT JOIN comments ON topics.id = comments.post_id 
      LEFT JOIN likes ON topics.id = likes.post_id 
      WHERE topics.to_user = 'someuser' 
      GROUP BY topics.id 
      ORDER BY score desc 
      LIMIT 0, 5;

Something like this should work:

SELECT likes.topic_id, comments.topic_id FROM likes,comments WHERE comments.topic_id = likes.topic_id AND likes.topic_id=[topicid]

That would return only the rows where the ids matched. Then you would just count rows. In php you would use: mysql_num_rows()

Supposing I want to query all posts with their author name, number of likes and comments, and the post body in one query. This is how it been done.

Using UNION

SELECT p.body, u.name, COUNT(lc.likes), COUNT(lc.comments)
FROM post p
JOIN user u ON p.uid=u.id
LEFT JOIN (
    SELECT pid, uid AS likes, NULL AS comments FROM like
    UNION
    SELECT pid, NULL, id FROM comment ) lc ON p.id = lc.pid
GROUP BY pid

I wrote this with the basic of SQL. You should know how to correct it if there is syntax error or so

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top