I'm developing a PHP + MySQL Project and need to know how to make a SQL query. Below there is a table sketch:
http://s24.postimg.org/na86w4do4/a_1.jpg
The ms_diseases
table stores disease names. The ms_characteristics
stores characteristics that may be from a certain disease. The ms_diseases_characteristics
table cross the relations between diseases and characteristics
Here it is an example:
http://s21.postimg.org/sg1f7kfti/b_1.jpg
The “Migraine” disease ( ms_diseases
) has the number 1 and 2 characteristics related in ms_diseases_characteristics
table.
Now the question is: How do I make a query that with the values 1 and 2 give back only the diseases with 1 and 2 characteristics? That In the specific case is “Migraine”?
Example:
Characteristics – 1, 2 – return -> MIGRAINE
Characteristics – 1 – return > NOTHING
Characteristics – 1, 4, 5 – return > FLU
Characteristics – 1, 4 – return > NOTHING
How do I make a query that returns the diseases with such characteristics?
SELECT disease_name
FROM
(
SELECT a.disease_name, c.totalCount
FROM ms_diseases a
INNER JOIN ms_diseases_characteristics b
ON a.ID = b.disease_ID
INNER JOIN
(
SELECT disease_ID, COUNT(*) totalCount
FROM ms_diseases_characteristics
GROUP BY disease_ID
) c ON b.disease_ID = c.disease_ID
WHERE b.characteristic_id IN (1,4,5) -- <<== list of charateristics
GROUP BY a.disease_name ^^
HAVING COUNT(*) = c.totalCount AND ^^
COUNT(DISTINCT b.characteristic_id) = 3 -- << # of parameters
) s
SELECT CASE WHEN A.COUNT = B.FOUND_DISES THEN M.DISEASE_NAME ELSE 'NOT FOUND' END AS DISEASE
FROM
(
SELECT COUNT(*) AS COUNT, DISEASE_ID
FROM MS_DISEASES_CHARACTERISTICS
GROUP BY DISEASE_ID
) A
JOIN
(
SELECT COUNT(*) AS FOUND_DISES, DISEASE_ID
FROM MS_DISEASES_CHARACTERISTICS
WHERE CHARACTERISTIC_ID IN (<VALUE YOU PASS>)
GROUP BY DISEASE_ID
) B
ON WHERE A.DISEASE_ID = B.DISEASE_ID
JOIN MS_DISEASES AS M
ON D.ID = A.DISEASE_ID
SELECT disease_name
FROM ms_diseases
WHERE id = (SELECT disease_id FROM (
SELECT disease_id, count(disease_id) CT
FROM
ms_diseases_characteristics AS dc,
ms_characteristics AS c
WHERE
c.id = dc.characteristic_id AND
c.id IN (1, 2)
GROUP BY disease_id
ORDER BY CT DESC) temp LIMIT 1);
Or if you want to use characteristics names instead:
SELECT disease_name
FROM ms_diseases
WHERE id = (SELECT disease_id FROM (
SELECT disease_id, count(disease_id) CT
FROM
ms_diseases_characteristics AS dc,
ms_characteristics AS c
WHERE
c.id = dc.characteristic_id AND
c.characteristic_name IN ('Headache','Frequent pain')
GROUP BY disease_id
ORDER BY CT DESC) temp LIMIT 1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.