我正在开发一个PHP + MySQL项目,需要知道如何进行SQL查询。 下面是一个表格草图:
http://s24.postimg.org/na86w4do4/a_1.jpg
ms_diseases
表存储疾病名称。
ms_characteristics
存储可能来自某种疾病的特征。
ms_diseases_characteristics
表跨越疾病与特征之间的关系
这是一个例子:
http://s21.postimg.org/sg1f7kfti/b_1.jpg
“偏头痛”疾病(ms_diseases
)在ms_diseases_characteristics
表中具有1和2个特征。
现在的问题是: 如何进行查询,使用值1和2仅返回具有1和2特征的疾病?那具体案例是“偏头痛”?
示例:
Characteristics – 1, 2 – return -> MIGRAINE
Characteristics – 1 – return > NOTHING
Characteristics – 1, 4, 5 – return > FLU
Characteristics – 1, 4 – return > NOTHING
如何进行返回具有此类特征的疾病的查询?
答案 0 :(得分:1)
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
答案 1 :(得分:0)
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
答案 2 :(得分:0)
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);
或者如果您想使用特征名称:
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);