sql语句条件

时间:2011-12-18 01:42:32

标签: asp.net sql database vb.net sql-server-2008

我想从患者表中选择区域=南或区域=西的所有女性患者,然后按疾病名称对结果进行分组 所以我不得不写下这样的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='" & "south" & " '" & "OR P.Area='" & "west" & " '" & " GROUP BY DiseaseName "

但这并没有返回正确的结果。

任何想法?

5 个答案:

答案 0 :(得分:1)

在您的OR条件周围加上括号

e.g。

WHERE P.Gender ='“&”female“&”'“&”AND (P.Area ='“&”south“&”'“&”OR P.Area ='“&”west“&”'“&”)

或只使用IN子句...... 其中p.gender ='female'和p.area in('south','west')

答案 1 :(得分:1)

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

你试图找到'南'或'西',而不是'南'或'西'。

您也可以修改此条件以使用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"

答案 2 :(得分: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 "

答案 3 :(得分:1)

您发布的查询无法正常工作的原因是因为您在生成的查询中的“west”和“south”之后有一个额外的空格。

您应始终使用()对逻辑进行分组,以便更轻松地维护和理解代码 - 并远离此类错误。

ANDOR更难绑定,所以你之前的内容与写作相同:

(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"

答案 4 :(得分: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 over OR

所以你有效地要求

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

您必须使用括号明确说明您需要的优先级

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