问题描述
|
我有一个数据库,该数据库的表具有标识符c1,c2,c3..etc等。
与其编写其中包含一堆ѭ0的查询,不如我如何用可以捕获以某个字母开头的所有记录的内容修改以下查询?
SELECT
Person.spineinjuryAdmit,tblComorbidity.comorbidityexplanation,Count(tblComorbidity.comorbidityexplanation) AS CountOfcomorbidityexplanation
FROM tblKentuckyCounties
INNER JOIN (tblComorbidity
INNER JOIN (Person
INNER JOIN tblComorbidityPerson
ON Person.PersonID = tblComorbidityPerson.personID)
ON tblComorbidity.ID = tblComorbidityPerson.comorbidityFK)
ON tblKentuckyCounties.ID = Person.County
GROUP BY Person.spineinjuryAdmit,tblComorbidity.comorbidityexplanation
HAVING (((Person.spineinjuryAdmit)=\"c1\" Or
(Person.spineinjuryAdmit)=\"c2\" Or
(Person.spineinjuryAdmit)=\"c3\"));
解决方法
SELECT Person.spineinjuryAdmit,tblComorbidity.comorbidityexplanation,Count(tblComorbidity.comorbidityexplanation) AS CountOfcomorbidityexplanation
FROM tblKentuckyCounties INNER JOIN (tblComorbidity INNER JOIN (Person INNER JOIN tblComorbidityPerson ON Person.PersonID = tblComorbidityPerson.personID) ON tblComorbidity.ID = tblComorbidityPerson.comorbidityFK) ON tblKentuckyCounties.ID = Person.County
GROUP BY Person.spineinjuryAdmit,tblComorbidity.comorbidityexplanation
HAVING (Person.spineinjuryAdmit LIKE \"c*\");
, 您是否尝试过使用LIKE
?举个例子:
SELECT * FROM patients WHERE lastName LIKE \'m%\';
这将返回patients.lastName
以\'m \'开头的记录。我不记得要访问的\'%\'字符是\'* \'。在某些数据库中,您也可以使用\'_ \'来匹配单个字符(或添加多个下划线)。
, 在执行GROUP BY之前,可以使用WHERE子句排除不需要的行。
SELECT
p.spineinjuryAdmit,c.comorbidityexplanation,Count(c.comorbidityexplanation) AS CountOfcomorbidityexplanation
FROM tblKentuckyCounties AS k
INNER JOIN (tblComorbidity AS c
INNER JOIN (Person AS p
INNER JOIN tblComorbidityPerson AS cp
ON p.PersonID = cp.personID)
ON c.ID = cp.comorbidityFK)
ON k.ID = p.County
WHERE p.spineinjuryAdmit ALike \"c%\"
GROUP BY p.spineinjuryAdmit,c.comorbidityexplanation
如果查询是在SQL-89模式下执行的,则可以将其用作WHERE子句。
WHERE p.spineinjuryAdmit Like \"c*\"
在SQL-92模式下,您需要标准ANSI通配符。
WHERE p.spineinjuryAdmit Like \"c%\"
我使用ALike告诉数据库引擎期望使用ANSI通配符。
DAO使用SQL-89模式...除非您已将数据库选项设置为使用SQL-92模式(“ SQL Server兼容语法”)。
如果您正在使用ADO运行查询,它将始终使用SQL-92模式。
, 您有两种选择:
使用LIKE运算子
使用IN运算子
例如:
Person.spineinjuryAdmit LIKE \"c*\"
Person.spineinjuryAdmit IN (\"c1\",\"c2\",\"c3\")
有关LIKE的详细信息,请参见http://office.microsoft.com/zh-cn/access-help/like-operator-HP001032253.aspx。
一般警告:Access中LIKE的通配符是*
和?
,而不是%
和_
(大多数其他版本的SQL都是这种情况)。
, 您可以对其进行修改,以将过滤器列表包括在“ 14”子句中。以下将查找姓氏以Smith
开头的患者。 (例如Smith
和Smithson
等),以及whose18ѭ以c
开头的人。
....
WHERE spineinjuryAdmit LIKE \'c*\'
AND Patient.FirstName LIKE \'Smith*\'
GROUP BY Person.spineinjuryAdmit,tblComorbidity.comorbidityexplanation;
, 您可以使用regexp查询以几个字符开头的所有行。
SELECT * FROM table WHERE column REGEXP \'^[ c1,c2,c3]\';
此查询将返回列以\'c1 \'或\'c2 \'或\'c3 \'开头的所有行。