我有一些 MySQL 代码正在尝试运行,但我不完全确定是否应该使用 IF 语句、IF 函数或 CASE 运算符来满足我的需要。我一直对我在网上阅读的内容感到困惑,我找不到任何地方可以用简单的术语列出如何以正确的语法使用它们中的任何一个而不变得复杂,所以如果这看起来很愚蠢,我深表歉意问题。
这里的代码有效:
SELECT
email,
accountgroup, othercode
FROM
(SELECT
email AS email,
accountgroup, othercode
FROM
accounts
UNION ALL
SELECT
email2 AS email,
accountgroup, othercode
FROM
accounts
UNION ALL
SELECT
email3 AS email,
accountgroup, othercode
FROM
accounts) account
WHERE
email LIKE '%@%'
AND accountgroup = '$row3' AND othercode = '$row4';
$row3 和 $row4 存储 POST 后的用户定义值。这些值将与数据库中列的值匹配,但是我还向此 POST 数据添加了 -all- 和 -none- 值,以便用户可以选择 -all- 或 -none- 帐户组。我的问题是,如果用户选择 -all- 或 -none,我不确定在 SQL 中做什么。我认为 IF 语句可以解决问题,但我的 SQL 出现错误,而且我很确定我没有正确使用 IF 语句。
IF ($row3= '-all-') THEN
SELECT
email,
accountgroup, othercode
FROM
(SELECT
email AS email,
accountgroup, othercode
FROM
accounts
UNION ALL
SELECT
email2 AS email,
accountgroup, othercode
FROM
accounts
UNION ALL
SELECT
email3 AS email,
accountgroup, othercode
FROM
accounts) account
WHERE
email LIKE '%@%'
AND accountgroup <> '' AND othercode = '$row3';
ELSEIF ($row3 = '-none-') THEN
SELECT
email,
accountgroup, othercode
FROM
(SELECT
email AS email,
accountgroup, othercode
FROM
accounts
UNION ALL
SELECT
email2 AS email,
accountgroup, othercode
FROM
accounts
UNION ALL
SELECT
email3 AS email,
accountgroup, othercode
FROM
accounts) account
WHERE
email LIKE '%@%'
AND accountgroup = '' AND othercode = '$row4';
ELSE
SELECT
email,
accountgroup, othercode
FROM
(SELECT
email AS email,
accountgroup, othercode
FROM
accounts
UNION ALL
SELECT
email2 AS email,
accountgroup, othercode
FROM
accounts
UNION ALL
SELECT
email3 AS email,
accountgroup, othercode
FROM
accounts) account
WHERE
email LIKE '%@%'
AND accountgroup = '$row3' AND othercode = '$row4';
END IF
非常感谢任何帮助,以及您能够提供的以新手方式解释 IF 语句/函数的任何来源。
最佳答案
这很大程度上取决于您 - 使用您想要的内容,但一般来说,当存在多个条件时使用 CASE,例如:
CASE ( value ) {
$a = 'a';
$a = 'b'
$a = 'c'
$a = 'd'
$a = 'e'
etc.
}
这样手机壳会看起来更好;添加额外字段也将更加容易。
如果您只有 2 个(或更多可能性)选项或多个选项下,则使用 IF:
IF ( $a = a ) {
IF ( $c = 2 && $d = 4 ) {
$b = 1
} ELSE {
$b = 2
}
} ELSE {
$b = 3
}
这是一般情况。但是如何以及何时使用女巫一号有很多选择。
PS:显示的数据只是简单的示例,与语法无关!
关于php - IF 语句、IF 函数还是 CASE?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19927776/