2011-12-18 140 views
1

我想从病人表中选择所有的女性患者,其中由病名 面积=朝南或面积=向西,然后组的结果所以我不得不写在那里的条件是这样的:SQL语句条件

command10.CommandText = "SELECT D.DiseaseName, COUNT(D.Patient_ID) AS PNO FROM PatientAffectDisease D INNER JOIN patient P on D.Patient_ID = P.Patient_ID WHERE P.Gender='" & "female" & "'" & " AND P.Area='" & "south" & " '" & "OR P.Area='" & "west" & " '" & " GROUP BY DiseaseName " 

但是这不会返回正确的结果。

任何想法?

+0

是大小写敏感的在你的数据库是否已开启?如果是这样的话,你可能需要处理所有的事情,以获得所需的匹配(当你想要使用索引时,它会真的很糟糕) – xQbert 2011-12-18 01:49:50

回答

1

在您的OR'd条件的周围放置括号

例如,

WHERE P.Gender ='” & “女性” & “ '” & “和 (P.Area ='” & “南” & “ '” & “OR P.Area ='” &“西“&”“ “&”)

或只使用IN子句... 其中p.gender = '女' 和p.area在( '南', '西')

+0

非常感谢你 – user1082487 2011-12-18 01:55:06

1

问题是否在南码和西码之后使用此代码还有额外的空格:" '"

您试图找到'south'或'west',而不是'south'或'west'。

您也可以修改此条件以使用IN子句。

command10.CommandText = "SELECT D.DiseaseName, COUNT(1) AS PNO FROM PatientAffectDisease D INNER JOIN patient P on D.Patient_ID = P.Patient_ID WHERE P.Gender='female' AND P.Area IN ('south', 'west') GROUP BY DiseaseName" 
1

我认为问题在于你的where子句中没有使用括号。

command10.CommandText = 
"SELECT D.DiseaseName, COUNT(D.Patient_ID) AS PNO " & _ 
" FROM PatientAffectDisease D " & _ 
" INNER JOIN patient P on D.Patient_ID = P.Patient_ID " & _ 
" WHERE P.Gender='female' AND P.Area in ('south','west') " _ 
" GROUP BY DiseaseName " 
1

您发布的查询无法正常工作的原因是您在生成的查询中'west'和'south'之后有额外的空间。

您应该始终将您的逻辑与()分组,以便更易于维护和理解代码 - 并远离此类错误。

AND结合比OR更难,所以你早些时候曾是一样的书写:

(P.Gender = 'female' AND P.Area = 'west') OR P.Area = 'south' -- not correct 

而不是使用P.Area = 'west' OR P.Area = 'south'可以使用IN运算符,如下面的例子:

SELECT  D.DiseaseName, COUNT(D.Patient_ID) AS PNO 
FROM  PatientAffectDisease D 
INNER JOIN patient P ON D.Patient_ID = P.Patient_ID 
WHERE  P.Gender = 'female' AND P.Area IN ('west','south') 
GROUP BY D.DiseaseName 

command10.CommandText = "SELECT D.DiseaseName, COUNT(D.Patient_ID) AS PNO FROM PatientAffectDisease D INNER JOIN patient P ON D.Patient_ID = P.Patient_ID WHERE P.Gender = 'female' AND P.Area IN ('west','south') GROUP BY D.DiseaseName" 
1

这是你查询的文本:

SELECT 
    D.DiseaseName, 
    COUNT(D.Patient_ID) AS PNO 
FROM PatientAffectDisease D 
    INNER JOIN patient P on D.Patient_ID = P.Patient_ID 
WHERE P.Gender='female' 
    AND P.Area='south ' 
    OR P.Area='west ' 
GROUP BY DiseaseName 

在SQL中,AND自然has precendence overOR

所以你实际询问

WHERE (P.Gender='female' AND P.Area='south') OR (p.Area = 'west') 

必须使用括号明确声明优先需要

WHERE P.Gender='female' AND (P.Area='south' OR p.Area='west') 
+0

+1格式良好的答案比其他答案要好。 – Lion 2011-12-18 02:00:45

+0

@狮子你是说我的帖子格式不正确? :O;) – 2011-12-18 02:02:46

+0

@refp :)没有,这根本不意味着。我也投了所有的答案。 – Lion 2011-12-18 02:11:06