我需要将此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
-----------------
答案 0 :(得分:4)
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