简体   繁体   English

MySQL在一个查询中计算多列

[英]MySQL Count multiple columns in one query

I've been using MySQL for just a day to handle my login system and i've come across a problem when creating a new user. 我已经使用MySQL一天来处理我的登录系统,而在创建新用户时遇到了一个问题。 I've got 3 fields i need to worry about, Display name, Username and Email . 我有3个字段需要担心, 显示名称,用户名和电子邮件 Now i need to check if any of the fields already have an entry in the database. 现在,我需要检查数据库中是否已有任何字段。 So if the display name that has been given is already in the database then it should show a message " This display name is already taken" and the same for the other 2. 因此,如果指定的显示名称已经存在于数据库中,则它应该显示一条消息“此显示名称已被使用” ,而其他2则显示相同的信息。

I've already read countless posts where people use SELECT COUNT and tons more but i still haven't been able to fit it in my own project. 我已经读了无数篇文章,人们在其中使用SELECT COUNT甚至更多,但我仍然无法将其放入我自己的项目中。

How would i go about doing this? 我将如何去做?

I was trying for way too long to find myself a solution for this, after a lot of trail and error i've made myself this bit of code. 经过很长时间的摸索和错误,我已经为自己准备了这段代码,所以我花了很长时间才找到解决方案。 It might not be perfect but it works just fine: 它可能并不完美,但效果很好:

string sql = "SELECT Nickname, Username, Email " 
        + " FROM UserData WHERE (Nickname=?Nickname OR Username=?Username OR  Email=?Email)";

MySqlCommand check = new MySqlCommand(sql, conn);
conn.Open();
check.Parameters.AddWithValue("?Nickname", txtCreateName.Text);
check.Parameters.AddWithValue("?Username", txtCreateUserName.Text);
check.Parameters.AddWithValue("?Email", txtCreateEmail.Text);
MySqlDataReader Reader;
Reader = check.ExecuteReader();

List<string> Nicknames = new List<string>();
List<string> Usernames = new List<string>();
List<string> Email = new List<string>();

while (Reader.Read())
{
    Nicknames.Add(Reader.GetString(0));
    Usernames.Add(Reader.GetString(1));
    Email.Add(Reader.GetString(2));
}
conn.Close();
Reader.Close();
Boolean alreadyexists = false;


if (Nicknames.Contains(txtCreateName.Text))
{
    alreadyexists = true;
    lblErrorDisplay.Visible = true;
}
if (Usernames.Contains(txtCreateUserName.Text))
{
    alreadyexists = true;
    lblErrorUsername.Visible = true;

}
if (Email.Contains(txtCreateEmail.Text))
{
    alreadyexists = true;
    lblErrorEmail.Visible = true;
}
if (alreadyexists)
{
    return;
}

If anyone has some improvements on this code it'll be much appreciated but this'll work for now. 如果有人对此代码进行了一些改进,将不胜感激,但是现在可以使用。

Just create UNIQUE INDEX on each of those fields. 只需在每个字段上创建UNIQUE INDEX That way you can be sure there wouldn't be any duplicates, because DB handle that internally. 这样,您可以确定不会有任何重复项,因为数据库是在内部处理的。 And also no race condition. 而且也没有比赛条件。

To handle duplicate insert, just check for specific error code. 要处理重复的插入,只需检查特定的错误代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM