2

我正在开发一个 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

如何进行查询以返回具有此类特征的疾病?

4

3 回答 3

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
于 2013-04-19T05:07:24.567 回答
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);
于 2013-04-19T06:30:27.023 回答
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
于 2013-04-19T05:39:38.917 回答