MySQL select 与 OR 运算符

MySQL select with OR operator

在 C# 桌面应用程序中我使用 MySqlConnection MySqlCommand cmd.CommandText:

"select * from reg where username='" + user + "' and password='" + pass + "' and key='" + key + "'";

选择记录,但我想弄清楚如何使用 OR 运算符和条件,如果我想同时检查 user OR email来自单个输入,例如 string UserOrEmail = textBox1.Text.Trim();.

看起来条件适用于 username=email=,但在这种情况下,以下值检查不起作用,看来我必须在这里使用一些正确的方法:

"select * from reg where username='" + UserOrEmail + "' or email='" + UserOrEmail + "' and password='" + pass + "' and key='" + key + "'";

您需要括号,因为运算符 AND 的优先级高于 OR:

"select * from reg where (username='" + UserOrEmail + "' or email='" + UserOrEmail + "') and password='" + pass + "' and key='" + key + "'";

或使用运算符IN:

"select * from reg where '" + UserOrEmail + "' in (username, email) and password='" + pass + "' and key='" + key + "'";