从多个表中选择?

时间:2016-05-28 18:53:58

标签: c# sql

enter image description here我有两个表,一个表的名称是(memberform),它有列id,名称,移动示例1,dimitris,69xxxxxxx,以及带列名称的第二个表(组), groupname,memberid示例dimitris,dancegroup,1(memberid与id相同) 我想提取到一个richtextbox,其中groupname from groups = combobox1,其中memberid来自groupname存在的行与memberform.id相同

我正在尝试这样的事情

using (var command = new SqlCommand("select mobile from memberform where memberform.id=groups.memberid and groups.groupname='" + comboBox1.Text + "'", con)) // 
using (var reader = command.ExecuteReader())

2 个答案:

答案 0 :(得分:1)

原始SQL查询是

SELECT M.mobile 
FROM memberform M 
JOIN groups G ON G.memberid = M.id 
WHERE G.groupname = 'dancegroup'

可以在sqlcommand中写入

using (var command = new SqlCommand("SELECT M.mobile FROM memberform M JOIN groups G ON G.memberid = M.id WHERE G.groupname = '" + comboBox1.Text + "'", con))

更新:

上述方法可以用于SQL注入攻击,因此明确地将参数传递给SqlParameter

using (var command = new SqlCommand("SELECT M.mobile FROM memberform M JOIN groups G ON G.memberid = M.id WHERE G.groupname = @GroupName", con))
{
    command.Parameters.Add(new SqlParameter("GroupName", comboBox1.Text);
    using (var reader = command.ExecuteReader())
    ....

答案 1 :(得分:0)

为什么不从第一个表中选择,获取数字然后用它从第二个表中选择?

@Edit:

private void GetData()
{
    // Get the ID using the name
    string id, yourData;
    SqlConnection con = new SqlConnection(connectionString);
    SqlCommand cmd = new SqlCommand("SELECT * FROM Table1 WHERE name=@name", con);
    cmd.Parameters.Add("@name", "dimitris");
    con.Open();
    SqlDataReader reader = cmd.ExecuteReader();
    while (reader.Read())
        id = reader["Id"].ToString();
    con.Close();

    // Get whatever you want using that ID
    cmd.CommandText = "SELECT * FROM Table2 WHERE Id=@id";
    cmd.Parameters.Add("@id", id);
    con.Open();
    reader = cmd.ExecuteReader();
    while (reader.Read())
        yourData = reader["ColumnName"].ToString();
    con.Close();
}