How to select a column conditionally according to another in MySQL

I have a table (users) that has the following columns:

userid  name  email  system_photo  personal_photo  photo_select

photo_selectcan have two values ​​(1 or 0). I want to select system_photoor personal_photoaccording to the value photo_select. If photo_select- 1, then you should choose personal_photo, otherwise if photo_select- 0, then you should choose system_photo.

Value

system_photocomes from another service. If the user does not like this photo, he / she can upload a new one. On another day, he / she will be able to switch between the two photos.

First I selected all three columns, and in the section for viewing my code, I wrote

if($user->photo_select === '0')
    echo $user->system_photo;
else if($user->photo_select === '1')
    echo $user->personal_photo;

, . (system_photo personal_photo) . MySQL SELECT ?

+4
3

:

select *, if(photo_select = 0, system_photo,personal_photo) as photo
from users

if , , 1 ... , , , , ,.....

+5
SELECT IF(photo_select = 1, personal_photo, system_photo) as photo from users
+4

try it

SELECT CASE
    WHEN photo_select=1 then personal_photo
    ELSE system_photo
END AS display_photo from users 
where userid=1
+1
source

All Articles