简体   繁体   English

如果mysql中的条件选择语句

[英]if condition in mysql select statement

Please help to solve the following issue. 请帮忙解决以下问题。 I've table called time_schedule. 我的表叫做time_schedule。
My Requirement is if start_city_name='somecity' then I need select departure_time 我的要求是如果start_city_name ='somecity'那么我需要选择departure_time
else I need to select arrival_time. 否则我需要选择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. 这里如果条件匹配则选择departure_time。 Then I need to select it as departure_time. 然后我需要选择它作为departure_time。
else if condition is failed arrival_time is selected,then I need to select the result as arrival_time. 否则,如果条件失败,则选择arrival_time,然后我需要选择结果作为arrival_time。 I'm Using MySQL. 我正在使用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. 条件为真时, arrival_time将为NULL ,条件为false时, departure_time将为NULL

Use a CASE construct like this: 使用像这样的CASE结构:

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. Google for CASE声明了解更多详情。 There are plenty of resources on this. 这有很多资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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