SQL Server使用两个表中的where条件连接两个表

时间:2013-11-28 13:22:52

标签: sql sql-server join

我有两个表clinical_study和location_countries,它们都有共同的NCT_ID(临床试验)字段,我必须从两个表中提取数据,在第一个表(性别)上应用条件,然后检查国家匹配第二张桌子, 我成功地设法运行以下查询,但它在国家/地区的领域我正在英国和其他国家/地区

select 
clinical_study.NCT_ID, clinical_study.BRIEF_SUMMARY, clinical_study.STUDY_TYPE, clinical_study.GENDER, location_countries.COUNTRY
from clinical_study

inner join location_countries
ON clinical_study.NCT_ID=location_countries.NCT_ID

where clinical_study.GENDER LIKE'Male' or clinical_study.GENDER like 'Both'

and  location_countries.COUNTRY ='United Kingdom'

NCT_ID ..... ..... BRIEF_SUMMARY ..... STUDY_TYPE ..... GENDER COUNTRY

XYS ........ XYZ ............... XYZ ............两个.......美国王国

XYS ........ XYZ ............... XYZ ............男.......法国

XYS ........ XYZ ............... XYZ ............男.......美国王国

XYS ........ XYZ ............... XYZ ............男.......瑞典

如果我在这里错过了一个技巧,请你建议

3 个答案:

答案 0 :(得分:2)

看起来你需要添加一些括号

select 
    clinical_study.NCT_ID, clinical_study.BRIEF_SUMMARY, clinical_study.STUDY_TYPE, clinical_study.GENDER, location_countries.COUNTRY
from clinical_study
inner join location_countries
ON clinical_study.NCT_ID=location_countries.NCT_ID
where (clinical_study.GENDER LIKE'Male' or clinical_study.GENDER like 'Both')
and  location_countries.COUNTRY ='United Kingdom'

答案 1 :(得分:1)

我认为AND优先于OR,因此将首先进行评估。因此,您可以使用括号来强制优先。

  where (clinical_study.GENDER LIKE'Male' or clinical_study.GENDER like 'Both')
  and  location_countries.COUNTRY ='United Kingdom'

答案 2 :(得分:1)

你的OR条款需要括号

where (clinical_study.GENDER LIKE'Male' or clinical_study.GENDER like 'Both')
and  location_countries.COUNTRY ='United Kingdom'