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)
Updated on: 2019-07-30T22:30:26+05:30

77 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements