Query from multiple tables in C#

huangapple go评论69阅读模式
英文:

Query from multiple tables in C#

问题

尝试从多个表中进行查询。

尽管我的代码对一个表有效,但我不知道如何在第二个表中进行搜索。

使用以下代码:

using (DataTable dt = new DataTable("Uniclass2015_EF_v1_12; Uniclass2015_En_v1_26"))
{
    using (SqlCommand cmd = new SqlCommand("select * from Uniclass2015_En_v1_26 where title like @Title; select * from Uniclass2015_EF_v1_12 where title like @Title", conn))
    {
        cmd.Parameters.AddWithValue("code", txtSearch.Text);
        cmd.Parameters.AddWithValue("Title", string.Format("%{0}%", txtSearch.Text));

        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        adapter.Fill(dt);

        dataGridView1.DataSource = dt;
    }
}

conn.Close();

我尝试在原始代码中添加了第二个表,但当我在搜索框中输入查询时,我收到一个空白的答案。

英文:

I am trying to query from multiple tables in one query.

Although my code is working for one table, I don't know how to search in the second table too.

using (DataTable dt = new DataTable("Uniclass2015_EF_v1_12; Uniclass2015_En_v1_26")) 
{
    using (SqlCommand cmd = new SqlCommand (" select *from Uniclass2015_En_v1_26  where title like @Title; select *from Uniclass2015_EF_v1_12  where title like @Title", conn))
    {
        cmd.Parameters.AddWithValue("code", txtSearch.Text);
        cmd.Parameters.AddWithValue("Title", string.Format("%{0}%", txtSearch.Text));

        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        adapter.Fill(dt);

        dataGridView1.DataSource = dt;
    }
}

conn.Close();

private void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)13)    // enter
        BtnSearch.PerformClick();
}

I tried to add a second table to my original code, but however when I type in the search box my query I receive a blank answer.

答案1

得分: 2

看起来你想在SQL中使用UNION运算符:

https://www.w3schools.com/sql/sql_union.asp

SELECT * FROM Uniclass2015_En_v1_26 WHERE title LIKE @Title UNION
SELECT * FROM Uniclass2015_EF_v1_12 WHERE title LIKE @Title

当然,这假设这两个表的列是相同的。如果你只需要从每个表中选择特定的列,只需选择那些列。

另外,我没有看到你在哪里使用你添加的code参数。

英文:

looks like you're wanting to use the UNION operator in SQL:

https://www.w3schools.com/sql/sql_union.asp

SELECT * FROM Uniclass2015_En_v1_26  WHERE title LIKE @Title UNION
 SELECT * FROM Uniclass2015_EF_v1_12  WHERE title LIKE @Title

This of course assumes the columns of the two tables are the same. If you only need specific columns from each, just select those columns.

Also, I don't see where you're using that code parameter you're adding

huangapple
  • 本文由 发表于 2023年2月9日 03:28:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75390828.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定