简体   繁体   中英

MySQL - Counting number by ID

Let's say I have this database (as an example)

在此处输入图像描述

Anyways, I want to make a "most liked" question section but the "likes" are in a different database table hence the likes . Anyways, I have the id of the question being the same thing in question_id ... but.. how do I count them in a MYSQL query?

Thanks.

What about using an inner join between your tables, and a group by on the question's ids:

select question.id, question.question_title, count(*) as num_likes
from question
    inner join likes on likes.question_id = question.id
group by question.id
order by count(*) desc
limit 0, 10

This should get you the 10 most-liked questions, with, for each one of those, the number of times it's been liked.

SELECT x.id,x.question_title,x.desc,x.category,COUNT(*) AS likes FROM question x LEFT JOIN likes y ON x.id=y.question_id GROUP BY x.id,x.question_title,x.desc,x.category ORDER BY COUNT(*) DESC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM