tags:

views:

36

answers:

3

I have two tables.

diseases

-----------------------------
| ID  |  NAME               |
-----------------------------
| 1   | Disease 1           |
| 2   | Disease 2           |
| 3   | Disease 3           |

diseases_symptoms

-----------------------------
| DISEASE_ID  | SYMPTOM_ID  |
-----------------------------
| 1           | 1           |
| 1           | 2           |
| 1           | 3           |
| 1           | 4           |
| 2           | 1           |
| 2           | 2           |

I want to select all diseses which have symptoms 1 or 2 and 3 or 4.

I've tried:

SELECT * 
 FROM diseases_symtoms 
WHERE (symptoms = '1' OR symptoms = '2') 
  AND (symptoms = '3' OR symptoms = '4')

And:

SELECT * 
  FROM diseases_symtoms 
  WHERE symptoms IN ('1','2') 
    AND symptoms IN ('3','4')

...but it is not working.

+1  A: 

Keep in mind that SELECT can only examine one row at a time. Both those queries act as if you can detect a 1 and a 3 simultaneously (for example), which is not possible.

To consider multiple rows at once, you can either join to two separate copies of the table, or try a grouping like this:

SELECT diseases.*
FROM diseases
INNER JOIN diseases_symptoms ON (disases_symptoms.disease_id = diseases.disease_id)
GROUP BY diseases.disease_id
HAVING SUM(IF(symptoms = 1 OR symptoms = 2, 1, 0) > 0 AND SUM(IF(symptoms = 3 OR symptoms = 4, 1, 0) > 0
VoteyDisciple
Thank you VoteyDisciple! It works perfect, but with little edit:SELECT diseases.*FROM diseasesINNER JOIN diseases_symptoms ON (disases_symptoms.disease_id = diseases.disease_id)GROUP BY diseases.disease_idHAVING SUM(IF(symptoms = 1 OR SYMPTOMS = 2, 1, 0)) > 0 AND SUM(IF(symptoms = 3 OR SYMPTOMS = 4, 1, 0)) > 0And again.. THANKS A LOT!!!
Deyan
Whoops. That is, of course, what I had in mind. I've edited for posterity.
VoteyDisciple
A: 
SELECT d.* FROM diseases AS d
INNER JOIN disease_symptoms AS s1 ON s1.DISEASE_ID = d.ID WHERE SYMPTOM_ID IN (1, 2)
INNER JOIN disease_symptoms AS s2 ON s2.DISEASE_ID = d.ID WHERE SYMPTOM_ID IN (3, 4)
GROUP BY d.ID
MrZebra
this not satsfies "1 OR 2 AND 3 OR 4."
Salil
Yah I just noticed that I misread the question, and have edited the post to reflect that condition
MrZebra
A: 

You could try...

SELECT DISTINCT *
    FROM diseases
    WHERE EXISTS (SELECT *
                       FROM disease_symptoms
                       WHERE disease.disease_id = disease_symptoms.disease_id AND
                             symptom_id IN (1,2)) AND
          EXISTS (SELECT *
                       FROM disease_symptoms
                       WHERE disease.disease_id = disease_symptoms.disease_id AND
                             symptom_id IN (3,4));
Brian Hooper