繁体   English   中英

Select 查询中有多个表 - SQL

[英]Select more than one tables in a query - SQL

我有 3 个表需要 select 各 2 列。 这些表称为EmployeeRank1EmployeeRank2EmployeeRank3 我只知道如何 select名称并从其中一张表中传递属性,即EmployeeRank1 但是,我需要 select名称并从所有三个表传递并将它们连接到单个查询。 你有什么建议吗? 这是我用于 select名称并从表EmployeeRank1传递的代码:

string query = "select * from EmployeeRank1 where Name = @name AND Password = @pass";

背后的想法是,如果 name 和 pass 的条目与存储在表中的条目匹配,则会打开 WPF 中的单独 window。 这是我的代码:

private void EmployeeRank1Button_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            string connectionString = ConfigurationManager.ConnectionStrings["CompanyManagementSystemm.Properties.Settings.ZaimovDBConnectionString"].ConnectionString;

            // create a query and select just the record we need 
            string query = "select * from EmployeeRank1 where Name = @name AND Password = @pass";

            // A local sqlconnection in a using statement ensure proper disposal at the end of this code 
            SqlConnection con = new SqlConnection(connectionString);
            con.Open();

            // Let the database do the work to search for the password and name pair
            SqlCommand cmd = new SqlCommand(query, con);
            cmd.Parameters.Add("@Name", SqlDbType.NVarChar).Value = tbName.Text;
            cmd.Parameters.Add("@pass", SqlDbType.NVarChar).Value = pbPassword.Password;
            SqlDataReader reader = cmd.ExecuteReader();

            // If the reader has rows then the user/pass exists in the db table
            if (reader.HasRows)
            {
                EmployeeRank1 employeeRank1 = new EmployeeRank1();
                employeeRank1.Show();
            }
            
        }
        catch (Exception exception)
        {
            MessageBox.Show(exception.ToString());
        }

你只是想要union / union all吗?

select name, pass from employeerank1
union 
select name, pass from employeerank2
union
select name, pass from employeerank3;

union会产生删除重复项的开销。 如果没有重复项或您不想删除它们,请使用union all

如果要在所有三个表中查找名称/通行证,可以使用:

select *
from (select name, pass from employeerank1
      union all
      select name, pass from employeerank2
      union all
      select name, pass from employeerank3
     ) er
where er.name = @name and er.pass = @pass;

暂无
暂无

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

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