我有一些我正在尝试使用的 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 语句/功能的任何资源。