如果条件在mysql中选择语句 [英] if condition in mysql select statement

查看:55
本文介绍了如果条件在mysql中选择语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助解决以下问题.我有一个名为time_schedule的表.
我的要求是,如果start_city_name ='somecity',那么我需要选择否则我需要选择arrival_time.在这里我想选择哪一个.例如:

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;

在这里,如果条件匹配,则选择"department_time".然后,我需要选择它作为发车时间".
否则,如果条件失败,则选择到达时间",那么我需要将结果选择为到达时间".我正在使用MySQL.预先感谢.

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;

这与简单地说:

SELECT arrival_time, departure_time
FROM time_schedule;

除了条件为true时, arrival_time 将为 NULL ,而当条件为true时, departure_time 将为 NULL .条件为假.

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

这篇关于如果条件在mysql中选择语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆