2013-02-12 137 views
8
select 
    disease_name 
from 
    disease 
where 
    disease_id= 
    (select disease_id from disease_symptom where 
     disease.disease_id=disease_symptom.disease_id AND 
     symptom_id= 
       (select symptom_id from symptom where symptom.symptom_id=disease_symptom.symptom_id 
       AND symptom_name='fever' OR symptom_name='head ache')) 

給出子查詢返回多個行的錯誤。原因是什麼?子查詢返回多於一行

+1

我想我會是一個明顯的例子:子查詢返回多行。 'disease_id'不能等於多個值。這個查詢最好用'JOIN'來代替子查詢。 – 2013-02-12 21:17:30

+0

http://stackoverflow.com/a/3423792/2806972 c這可能會得到這個Q的解決方案: – 2014-04-05 08:03:04

回答

2

打破查詢下來,你有

主查詢:

select disease_name from disease where disease_id= 

子查詢1:

select disease_id from disease_symptom where 
     disease.disease_id=disease_symptom.disease_id AND 
     symptom_id= 

子查詢2:

select symptom_id from symptom where symptom.symptom_id=disease_symptom.symptom_id 
      AND symptom_name='fever' OR symptom_name='head ache' 

由於您使用等號,子查詢cann ot返回多個項目。看起來子查詢2由於使用了OR而有更大的機會返回2個項目。您不妨嘗試IN子句,如WHERE symptom_id IN (sub-query2)WHERE disease_id IN (sub-query1)

14

您的兩個外部查詢的結構是希望從其子查詢得到單個結果。但是,如果你有結構化的東西,你的子查詢可能會返回多個結果。如果你真的想不止一個結果,重組這樣的:

... where disease_id IN (subquery returning multiple rows...) 

此外,子查詢是殺人的性能,它的成倍wosrse爲嵌套子查詢。您可能需要考慮使用INNER JOIN