两个表中的 Select 列以及 'Like' 语句

Select columns from Two Tables along with 'Like' statement

我正在为我的网站编写搜索功能,我需要扫描两个 table 和 select 行,其中包含我发送的特定字符串(使用 LIKE)。我写了这个,但它没有发回任何东西。

SqlCommand cmd = new SqlCommand("Select * From Table1, Table2 where Name LIKE '" + searchText + "%' OR Table2 where Name LIKE '" + searchText + "%'", con);

基本上从 BOTH table 中获取与我发送的字符串相似的行的所有行。扫描 table 的两个列以查找我使用 'LIKE'

发送的特定字符串

列名称不同:)

这是执行此操作的正确方法吗?

试试这个

SqlCommand cmd = new SqlCommand("Select * From Table1 tbl1, Table2 tbl2 where tbl1.Name LIKE '" + searchText + "%' OR tbl2.Name LIKE '" + searchText + "%'", con);

如果你确认两个表有相同的列,你可以使用这个查询;

Select * From Table1
where Name LIKE '" + searchText + "%' 
UNION ALL
Select * From Table2 
where Name LIKE '" + searchText + "%'

你的代码有几个问题。

最严重的是您使用字符串连接而不是 parameters
这使您的代码非常容易受到 SQL injection attacks.

第二个是你的SQL完全错了。
您正在使用没有任何连接条件的隐式连接。
这使得 cross join,但我不确定这是否是您想要的。
始终使用显式连接。即 from t1 inner join t2 on(t1.id = t2.id).
隐式连接已经过时 20 多年了。
阅读 this and that 以获取有关隐式连接和显式连接之间差异的更多信息

我不会给你一个SQL建议,因为它不是很清楚你想要的结果是什么,但是如果你想写出好的代码,你必须考虑我提出的几点。

更新
根据您的评论,您可能可以这样做:

declare @Name varchar(10)='as'

SELECT Table1.*, Table2.*
FROM (
    SELECT t1_Id As Id, 1 As TableNumber
    FROM Table1 
    WHERE t1_Name LIKE @Name+'%'

    UNION ALL

    SELECT t2_Id as Id, 2 As TableNumber
    FROM Table2 
    WHERE t2_Name LIKE @Name+'%'
) SearchResults
LEFT JOIN Table1 ON(t1_Id = Id AND TableNumber = 1)
LEFT JOIN Table2 ON(t2_Id = Id AND TableNumber = 2)

see sql fiddle here