Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if condition in mysql select statement

Please help to solve the following issue. I've table called time_schedule.
My Requirement is if start_city_name='somecity' then I need select departure_time
else I need to select arrival_time. Here I want to which one is selected. For ex:

SELECT IF(start_city_name='somecity',departure_time,arrival_time) 
   FROM time_schedule;

here if condition is matched departure_time is selected. Then I need to select it as departure_time.
else if condition is failed arrival_time is selected,then I need to select the result as arrival_time. I'm Using MySQL. Thanks in Advance.

like image 434
Srinivas Avatar asked Sep 03 '25 14:09

Srinivas


1 Answers

To know which one is selected, you can do something like this:

SELECT IF(start_city_name='somecity', 'Departure time', 'Arrival time'),
       IF(start_city_name='somecity', departure_time, arrival_time)
FROM time_schedule;

You can't really have it as the column name, what if there's one row where the condition is true and one where the condition is false, what should the column name be?

However, if you're happy splitting them into 2 columns:

SELECT IF(start_city_name='somecity', NULL, arrival_time) AS 'Arrival time',
       IF(start_city_name='somecity', departure_time, NULL) AS 'Departure time'
FROM time_schedule;

This is very similar to simply saying:

SELECT arrival_time, departure_time
FROM time_schedule;

Except that arrival_time will be NULL when the condition is true, and departure_time will be NULL when the condition is false.

like image 169
Bernhard Barker Avatar answered Sep 05 '25 05:09

Bernhard Barker