简体   繁体   中英

Joining 2 mysql table and ordering by number of same rows in 1 table

I need some help with a mysql query.

I have 2 tables,

Table 1 - Photos (photo_id, photo_url)

1----- www.someurl.com
2----- www.someurl.com
3----- www.someurl.com
4----- www.someurl.com

Table 2 - Favorites (favorite_id, user_id,photo_id)

1-------5------1
2-------5------2
3-------6------1
4-------6------3
5-------7------2
6-------7------3
7-------8------3
7-------8------4

I want to get results from photos table ordering by the favorite numbers of users.

Correct ordering must be:

1) Photo-3 (3 votes)
2) Photo-2 (2 votes)
2) Photo-1 (2 votes)
2) Photo-4 (1 vote)

SELECT  a.photo_url, COUNT(b.photo_ID) totalVotes
FROM    table1 a
        LEFT JOIN table2 b
            ON a.photo_ID = b.photo_id
GROUP BY a.photo_url
ORDER BY totalVotes 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