简体   繁体   English

如何在mysql select语句中实现if else条件

[英]How to implement If else condition in mysql select statement

I want to check the value present in two fields of the table and based on that i want to display either field 1 or field 2. For Example: 我想检查表的两个字段中存在的值,并根据该值显示字段1或字段2。例如:

Select name from users if address1='Mars' 
else select age from users if address2='Mars';

I want to achieve this using plane sql because I need to implement this in the controller of rails using ActiveRecord::Base.connection.select_values("sql query") 我想使用平面sql实现此功能,因为我需要使用ActiveRecord::Base.connection.select_values("sql query")在rails控制器中实现此功能

What should be the SQL query to achieve the same. 要实现相同的SQL查询应该是什么。 I could not find it anywhere. 我在任何地方都找不到。 Thanks in advance. 提前致谢。

use CASE 使用CASE

SELECT  CASE 
            WHEN address1='Mars' THEN name 
            WHEN address2='Mars' THEN age
        END
FROM    users

请尝试User.find_by_sql("your sql query")

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

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