从多个表中选择具有变量输入的语句
我有两个表: AreaCode
和EquipmentNumber
。
+------------------------------------+ | AreaCd | |------------------------------------| | AreaID INT NOT NULL AUTO_INCREMENT | | Code INT | | Name CHAR(30) | | Comments TEXT | | PKEY (AreaID) | +------------------------------------+ +------------------------------------+ | EqNum | |------------------------------------| | EqID INT NOT NULL AUTO_INCREMENT | | AreaID INT | | Number CHAR(5) | | Type CHAR(10) | | PKEY (EqID) | | FKEY (AreaID) REF AreaCode(AreaID) | +------------------------------------+
我想提取EqNum.Number
, Eq.Type
和AreaCd.Code
。 问题是,查询是由表单输入填充的,因此搜索限制是可变的。 我创建了3个与此类似的单独查询:
"SELECT Number, Type, Code FROM EqNum, AreaCd " + "WHERE EqNum.AreaId = AreaCd.AreaId AND Code = " + int nCode + ";"; "SELECT Number, Type, Code FROM EqNum, AreaCd " + "WHERE EqNum.AreaId = AreaCd.AreaId AND Number = '" + string sNumber + "';"; "SELECT Number, Type, Code FROM EqNum, AreaCd " + "WHERE EqNum.AreaId = AreaCd.AreaId AND Type = '" + string sType + "';";
如果用户一次只搜索一列( Code
, Number
或 Type
),这一切都可以自行完成,但我需要能够一次搜索一列,两列或全部三列。
我尝试过使用OR
, LIKE
,多选,我甚至尝试将int nCode
作为char来使用%
通配符,但我找不到有用的东西。
问题:有人可以帮我加入这三个查询来搜索表中所有三个字符串的任意组合: EqNum.Number
, EqNum.Type
和AreaCd.Code
,它们会在添加更多字段时优化搜索结果吗? (即搜索EqNum.Type
将产生比搜索EqNum.Number
, EqNum.Type
和AreaCd.Code
更多的结果)
SELECT e.Number, e.Type, a.Code FROM EqNum e INNER JOIN AreaCd a ON e.AreaId = a.AreaId WHERE (@Number IS NULL OR e.Number = @Number) AND (@Type IS NULL OR e.Type = @Type) AND (@Code IS NULL OR a.Code = @Code)
要了解如何在ADO.NET中使用参数, 请单击此处 。
设置参数看起来像这样:
command.Parameters["@Number"].Value = (string.IsNullOrEmpty(number) ? (object) DBNull.Value : number);
我想这就是你所追求的:
刚添加一个简单的技巧;
if(string.IsNullOrEmpty(sNumber)) sNumber="$$$"; //If sNumber is empty, then selection using sNumber= '$$$' will return nothing. if(string.IsNullOrEmpty(sType)) sType="$$$" //If sType is empty, then selection using sType = '$$$' will return nothing. "SELECT Number, Type, Code FROM EqNum, AreaCd " + "WHERE EqNum.AreaId = AreaCd.AreaId AND (Code = " + int nCode + " OR Number = '" + string sNumber + "' OR Type = '" + string sType + "')"
或使用LIKE
:
if(string.IsNullOrEmpty(sNumber)) sNumber="$$$"; //If sNumber is empty, then selection using sNumber LIKE '%$$$%' will return nothing. if(string.IsNullOrEmpty(sType)) sType="$$$" //If sType is empty, then selection using sType LIKE '%$$$%' will return nothing. "SELECT Number, Type, Code FROM EqNum, AreaCd " + "WHERE EqNum.AreaId = AreaCd.AreaId AND (Code = " + int nCode + " OR Number LIKE '%" + string sNumber + "%' OR Type LIKE '%" + string sType + "%')"
查看SQL Fiddle的示例
试试这个
SELECT Number, Type, Code FROM EqNum, AreaCd " + "WHERE EqNum.AreaId = AreaCd.AreaId AND isnull(Code,0) = " + int nCode + " or isnull(Number,0) = '" + string sNumber + "' or isnull(Type,0) = '" + string sType + "'