How to retrieve a value with MySQL count() having maximum upvote value?


Let’s say we have some columns in the table, one for image path and another for the upvotes. However, the first column is the auto increment Id as shown below −

mysql> create table DemoTable(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,ImagePath varchar(100),UpvoteValue int
);
Query OK, 0 rows affected (0.72 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(ImagePath,UpvoteValue) values('Image1.jpeg',90);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable(ImagePath,UpvoteValue) values('Image2.jpeg',10);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable(ImagePath,UpvoteValue) values('Image3.jpeg',120);
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable(ImagePath,UpvoteValue) values('Image4.jpeg',114);
Query OK, 1 row affected (1.17 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+-------------+-------------+
| Id | ImagePath   | UpvoteValue |
+----+-------------+-------------+
| 1  | Image1.jpeg | 90          |
| 2  | Image2.jpeg | 10          |
| 3  | Image3.jpeg | 120         |
| 4  | Image4.jpeg | 114         |
+----+-------------+-------------+
4 rows in set (0.00 sec)

Here is the query to retrieve imagepath value with count() having max upvote value −

mysql> select ImagePath from DemoTable where UpvoteValue IN (select max(UpvoteValue) from DemoTable);

This will produce the following output >

+-------------+
| ImagePath   |
+-------------+
| Image3.jpeg |
+-------------+
1 row in set (0.00 sec)

Updated on: 22-Aug-2019

71 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements