我正在 PHP 变量中编写此代码,其中 $username 和 $email 被替换。我在屏幕上回显了这一点,看起来是正确的。我假设 MySQL 代码存在问题,因为我总是得到的唯一结果是“可接受”。有什么帮助吗?
SELECT CASE
WHEN email='$email' THEN '$email is already associated with an account'
WHEN username='$username' THEN '$username is already taken'
ELSE 'acceptable'
END AS result FROM collaborator
UNION
SELECT CASE
WHEN email='$email' THEN '$email is already associated with an account'
WHEN username='$username' THEN '$username is already taken'
ELSE 'acceptable'
END AS result
FROM waitForValidation
LIMIT 1;
最佳答案
您的问题是在一个或另一个表中无法匹配,因此 'acceptable'
来自某处。然后,您使用union
,它通常通过排序来删除重复项。尝试以不同的方式进行匹配:
select (case when max(email) = $email then '$email is already associated with an account'
when max(username)='$username' THEN '$username is already taken'
else 'acceptable'
end)
from (select email, username
from collaborator
where email = '$email' or username= '$username'
union
select email, username
from waitForValidation
where email = '$email' or username= '$username'
) t
这使用 max()
而不是 limit
来处理没有匹配项的情况。在这种情况下,max()
将返回 NULL
,因此前两个条件将失败。
关于mysql - 无法弄清楚为什么每个查询都返回 else (情况时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17434437/