英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论