mysql select语句中的if条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18843840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 18:52:46  来源:igfitidea点击:

if condition in mysql select statement

mysqlselectif-statement

提问by Srinivas

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:

请帮助解决以下问题。我有一个名为 time_schedule 的表。
我的要求是如果 start_city_name='somecity' 那么我需要选择离开时间
否则我需要选择到达时间。这里我要选择哪一个。例如:

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.

在这里,如果条件匹配,则选择离开时间。然后我需要选择它作为admission_time。
否则,如果条件失败,选择了到达时间,那么我需要选择结果作为到达时间。我正在使用 MySQL。提前致谢。

回答by Bernhard Barker

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:

但是,如果您愿意将它们分成 2 列:

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_timewill be NULLwhen the condition is true, and departure_timewill be NULLwhen the condition is false.

除了arrival_timeNULL当条件为真,departure_time将是NULL当条件是假的。

回答by Rachcha

Use a CASEconstruct like this:

使用这样的CASE构造:

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

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

谷歌CASE声明了解更多详情。这方面有很多资源。