简体   繁体   中英

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.

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.

Use a CASE construct like this:

SELECT CASE start_city
         WHEN 'somecity' THEN departure_time
         ELSE arrival_time
       END AS column_alias
  FROM time_schedule;

Google for CASE statements for more details. There are plenty of resources on this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM