【问题标题】:Converting PHP conditional statement to MySQL if-then conditional statement将 PHP 条件语句转换为 MySQL if-then 条件语句
【发布时间】:2012-07-16 22:54:56
【问题描述】:

我需要将此 PHP 代码转换为等效的 MySQL 查询

$name = 'John Doe';
if($citizenship == 'o') {
  if($country == 'US') {
    $status = 'US-INTL';
  }else{
    $status = 'INTL';
  }
} elseif {
  $status = 'US'
}    

我在使用 MySQL 的 if-then 语句时遇到了问题,即使在阅读了它们非常少的 documentation 之后也是如此。我尝试了不同的嵌套技术,但它们都失败了,因为我不知道语法。例如:

SELECT name, IF citizenship='US' THEN 
  IF country='US' THEN 'US-INTL' AS status
  ELSEIF 'INTL' AS status
ELSE 
  'US' AS status
END IF
FROM people

MySQL 应该返回类似的东西

_________________
name     | status
-----------------
John Doe | US-INTL
-----------------

【问题讨论】:

    标签: mysql if-statement conditional-statements


    【解决方案1】:
    SELECT name,
           CASE WHEN citizenship = 'US'
                THEN CASE WHEN country='US'
                          THEN 'US-INTL'
                          ELSE 'INTL'
                     END
                ELSE 'US'
           END status
    

    或mysql特有的方式:

    SELECT name,
           IF(citizenship = 'US',
              IF(country='US', 'US-INTL', 'INTL'),
              'US') status
    

    【讨论】:

    • 彩蛋!两个都有效。我会选择第一个,因为它对我来说更有意义并且更具可读性。
    猜你喜欢
    • 1970-01-01
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    • 1970-01-01
    • 2019-04-21
    • 2011-05-10
    • 1970-01-01
    相关资源
    最近更新 更多