在另一个查询中使用SQL查询结果

时间:2016-01-31 05:42:55

标签: c# mysql sql-server datagridview

所以我填写了一个名字列表的组合框。现在点击其中一个名字后我执行

SELECT Id FROM FIRSTTABLE WHERE Name ='" + ClientComboBox.Text + "'

现在我想获取该Id并在SECONDTABLE中执行另一个Sql查询。但是,SECONDTABLE Id称为ClientId。另外,我想只填充一次datagridview。因此,我不希望事件显示FIRSTTABLE结果,只有我从SECONDTABLE结果中得到的结果。不确定这一切是否有意义,所以如果您有任何问题请告诉我。

private void ClientComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {

            var myConnection = new SqlConnection(DBConnectionBox.Text);
            //myConnection.Open();


            var Cmd = new SqlCommand("SELECT Id FROM FIRSTTABLE WHERE Name ='" + ClientComboBox.Text + "';");
            Cmd.Connection = myConnection;
            Cmd.CommandType = CommandType.Text;

            var Cmd2 = new SqlCommand("SELECT * FROM SECONDTABLE WHERE ClientId ='"+"';");
            Cmd2.Connection = myConnection;
            Cmd2.CommandType = CommandType.Text;

            SqlDataAdapter sqlDataAdap = new SqlDataAdapter(Cmd);
            SqlDataAdapter sqlDataAdap2 = new SqlDataAdapter(Cmd2);

            DataTable dtRecord = new DataTable();
            DataTable dtRecord2 = new DataTable();

            sqlDataAdap.Fill(dtRecord);
            sqlDataAdap2.Fill(dtRecord2);

            ClientInfoDGV.DataSource = dtRecord;
            ClientInfoDGV.DataSource = dtRecord2;
        }

2 个答案:

答案 0 :(得分:2)

听起来你想使用内连接。

var Cmd = new SqlCommand(@"SELECT Id, SECONDTABLE.* FROM FIRSTTABLE
   JOIN SECONDTABLE ON FIRSTTABLE.Id = SECONDTABLE.ClientId  
   WHERE Name ='" + ClientComboBox.Text + "';")

答案 1 :(得分:0)

在单个查询中使用

SELECT * 
FROM   secondtable 
WHERE  clientid IN (SELECT f.id 
                    FROM   firsttable f
                    WHERE  f.NAME = "clientcombobox.text") 

Exists(优先)

SELECT * 
FROM   secondtable s 
WHERE  EXISTS(SELECT 1 
              FROM   firsttable f 
              WHERE  s.clientid = f.id 
                     AND f.NAME = "clientcombobox.text")