如何从 SQL 服务器中的两个表中获取不同的行
How to get different rows from two tables in SQL Server
我正在尝试构建一个可以为我提供两个表之间不同行的查询。
这是我的代码:
try
{
string searchquery = "SELECT* FROM NewList EXCEPT SELECT* FROM Restaurants UNION All";
SqlCommand searchcom = new SqlCommand(searchquery, connection);
SqlDataAdapter da = new SqlDataAdapter(searchcom);
DataSet ds = new DataSet();
connection.Open();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
connection.Close();
}
catch (Exception er)
{
Debug.WriteLine(er.Message);
return;
}
我收到以下错误:
Incorrect syntax near 'All'.
在SqlCommand
class中使用Union All
的正确way/syntax是什么?我试图以多种方式将它作为我的查询字符串,但每次都给我同样的错误。如何在我的搜索查询中使用正确的语法实现它?
您的查询从 UNION ALL
开始不正确。
你可以这样试试:
string searchquery = "SELECT * FROM NewList UNION ALL SELECT * FROM Restaurants ";
但是,您需要注意:
- 它不会删除各种
SELECT
语句之间的重复行(返回所有行)
UNION ALL
中的每个 SELECT
语句在具有相似数据类型的结果集中必须具有相同数量的列
阅读 here 了解更多详情。
已更新
如果你想在一个 table 中获取另一个不存在的行,你应该使用 EXCEPT
而不是 UNION ALL
。
Select Checking.RestID, FROM
(SELECT RestID FROM NewList EXCEPT Select RestID from Restaurants) as Checking
LEFT JOIN NewList ON Checking.RestID = NewList.RestID
这成功了,感谢任何人!
我正在尝试构建一个可以为我提供两个表之间不同行的查询。
这是我的代码:
try
{
string searchquery = "SELECT* FROM NewList EXCEPT SELECT* FROM Restaurants UNION All";
SqlCommand searchcom = new SqlCommand(searchquery, connection);
SqlDataAdapter da = new SqlDataAdapter(searchcom);
DataSet ds = new DataSet();
connection.Open();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
connection.Close();
}
catch (Exception er)
{
Debug.WriteLine(er.Message);
return;
}
我收到以下错误:
Incorrect syntax near 'All'.
在SqlCommand
class中使用Union All
的正确way/syntax是什么?我试图以多种方式将它作为我的查询字符串,但每次都给我同样的错误。如何在我的搜索查询中使用正确的语法实现它?
您的查询从 UNION ALL
开始不正确。
你可以这样试试:
string searchquery = "SELECT * FROM NewList UNION ALL SELECT * FROM Restaurants ";
但是,您需要注意:
- 它不会删除各种
SELECT
语句之间的重复行(返回所有行) UNION ALL
中的每个SELECT
语句在具有相似数据类型的结果集中必须具有相同数量的列
阅读 here 了解更多详情。
已更新
如果你想在一个 table 中获取另一个不存在的行,你应该使用 EXCEPT
而不是 UNION ALL
。
Select Checking.RestID, FROM
(SELECT RestID FROM NewList EXCEPT Select RestID from Restaurants) as Checking
LEFT JOIN NewList ON Checking.RestID = NewList.RestID
这成功了,感谢任何人!