- 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
MySQL select any one field out of two with respect to the value of a third field?
For this, use IF(). Let us first create a table −
mysql> create table DemoTable -> ( -> PlayerName varchar(100), -> PlayerScore int, -> PlayerStatus varchar(100) -> ); Query OK, 0 rows affected (0.58 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('John',88,'BAD'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('Chris',78,'BAD'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('Robert',90,'BAD'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values('David',80,'BAD'); Query OK, 1 row affected (0.23 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
Output
+------------+-------------+--------------+ | PlayerName | PlayerScore | PlayerStatus | +------------+-------------+--------------+ | John | 88 | BAD | | Chris | 78 | BAD | | Robert | 90 | BAD | | David | 80 | BAD | +------------+-------------+--------------+ 4 rows in set (0.00 sec)
Following is the query to select any one field out of two with respect to the value of a third field −
mysql> select PlayerScore,if(PlayerScore > 80 , PlayerName ,PlayerStatus) AS Result from DemoTable;
Output
+-------------+--------+ | PlayerScore | Result | +-------------+--------+ | 88 | John | | 78 | BAD | | 90 | Robert | | 80 | BAD | +-------------+--------+ 4 rows in set (0.00 sec)
Advertisements