Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the most frequently occurring item in table

Tags:

sql

mysql

I am making a library database and I am having a problem in one place. I need to find most popular borrowed book. I have these tables.

--Books--          --BookReader--             --Readers--
book_id              book_id                    reader_id
                 reader_id                  

FOR EXAMPLE DATA IN TABLE BookReader;

----BookReader---
reader_id book_id
1        |    2
1        |    3
3        |    2

I think I need to count every book_id in BookReader which is equal(2, 3 and so on) and than find that max number.

I can't write the SQL query to find most popular borrowed book(bookId)?

like image 512
Donatas Vileita Avatar asked Jan 26 '26 11:01

Donatas Vileita


1 Answers

select book_id,count(book_id) as buys
from BookReader
group by book_id
order by buys desc
limit 1

Here is the SQLFiddle

like image 183
Ashish Gaur Avatar answered Jan 29 '26 08:01

Ashish Gaur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!