Skip to content
Advertisement

Remove specific fields and show other fields in Mysql

I would like to ask for ways to solve this MySQL issue. Currently, I have this select query

SELECT username, friend_username from friends
WHERE (username = "apple" or friend_username = "apple");

and it shows this Friends Table (below).

Friends Table
------------------------------
| username | friend_username |
------------------------------
| apple    | orange          |
| apple    | pear            |
| durian   | apple           |
------------------------------

But I would like to execute a select query to make it look like this (below).

------------
| username |  
------------
| orange   |
| pear     |
| durian   |
------------

Is there any possible ways to achieve this? Appreciate the help! Thank you.

Advertisement

Answer

I would write this as:

select case when username = 'apple' then friend_username else username end username
from friends
where 'apple' in (username, friend_username);

The where clause uses in to filter on rows where either username or friend_username is equal to 'apple'. Then, the case expression in the select clause displays the “other” column.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement