我有一些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- accountgroups。我的问题是,如果用户选择-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声明/功能的任何来源。
答案 0 :(得分:0)
它几乎取决于你 - 使用你想要的东西,但一般来说,当有多种情况时使用CASE,例如:
CASE ( value ) {
$a = 'a';
$a = 'b'
$a = 'c'
$a = 'd'
$a = 'e'
etc.
}
这样一个案子看起来会更好;并且添加额外的字段也会更容易。
如果您只有2个(或更多可能性)选项或多个 under-options ,请使用IF:
IF ( $a = a ) {
IF ( $c = 2 && $d = 4 ) {
$b = 1
} ELSE {
$b = 2
}
} ELSE {
$b = 3
}
总的来说。但是有很多选择如何以及何时使用女巫。
PS:显示的数据只是简单的示例,与语法无关!
答案 1 :(得分:0)
如果需要,您可以在查询的某些列中使用CASE或IF。但在这种情况下,您有整个SQL查询的条件。只需在PHP中保持这种条件处理,就不需要在SQL语句中执行它。
答案 2 :(得分:0)
根据我在php中使用它并使用switch case,因为它比if else条件快得多
更多关于这一点,如果你真的想在sql中有条件那么请用例。
更好地了解mysql中的case语句
http://dev.mysql.com/doc/refman/5.0/en/case.html
更好地了解mysql中的if语句
http://dev.mysql.com/doc/refman/5.0/en/if.html