- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to fetch a specific row when values are the same in MySQL?
To fetch a specific row when values are the same, use GROUP BY. Let us first create a table −
mysql> create table DemoTable659(Id int,Name varchar(100),Score int); Query OK, 0 rows affected (0.52 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable659 values(11,'John',45); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable659 values(15,'John',59); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable659 values(15,'Sam',61); Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable659;
This will produce the following output −
+------+------+-------+ | Id | Name | Score | +------+------+-------+ | 11 | John | 45 | | 15 | John | 59 | | 15 | Sam | 61 | +------+------+-------+ 3 rows in set (0.00 sec)
Here is the query to fetch a specific row when values are the same −
mysql> select *from ( select *from DemoTable659 order by Id desc) tbl group by Name;
This will produce the following output −
+------+------+-------+ | Id | Name | Score | +------+------+-------+ | 11 | John | 45 | | 15 | Sam | 61 | +------+------+-------+ 2 rows in set (0.04 sec)
Advertisements