SQL - 表之间的关系

时间:2014-05-19 22:42:43

标签: mysql sql sql-server

我正在制作一种药物数据库,它有三个主要表格:药物,ActiveIngredients和第三个用于药物和活性成分之间联系的表格,例如MedicationsActiveIngredients。 表这样的药物

MedicationID - MedicationName

M1 - 药物治疗#1

M2 - 药物治疗#2

M3 - 药物#3

等等

表ActiveIngredients就是这样

ACtiveIngredientID - ActiveIngredientName

AI1 - 活性成分#1

AI2 - 活性成分#2

AI3 - 活性成分#3

等等

表MedicationsActiveIngredients看起来像这样

MedicationID - ActiveIngredientID

如果药物#1有两种活性成分;活性成分1和活性成分2,我在第三个表中添加两行,如下所示

M1 - AI1

M1 - AI2

如果我想得到一个mediaction的活性成分列表,我使用这个SQL查询

SELECT ActiveIngredients.ActiveIngredientName
FROM ActiveIngredients, MedicationsActiveIngredients
WHERE ActiveIngredients.ActiveIngredientID = MedicationsActiveIngredients.ActiveIngredientID
AND MedicationsActiveIngredients.MedicationID = 'M1'

问题是:

1-我的结构是否形成良好?或者它可以以更好的方式配制?

2-我怎样才能获得含有活性成分组合的药物清单(假设药物中含有活性成分#1 +活性成分#2?

3-如何获得具有相似成分(含有一种或多或少活性成分)的药物清单到另一种药物?

我正在使用MSSQL(在Windows窗体应用程序中)和MySQL(在网站中)

1 个答案:

答案 0 :(得分:1)

使用现代连接语法

 SELECT ActiveIngredients.ActiveIngredientName
 FROM ActiveIngredients, 
      inner join MedicationsActiveIngredients
           ON ActiveIngredients.ActiveIngredientID = MedicationsActiveIngredients.ActiveIngredientID
      WHERE MedicationsActiveIngredients.MedicationID = 'M1'

寻找含有常见成分的配方

select MedicationID
from MedicationsActiveIngredients 
where ActiveIngredientID in (2,3) 
group by MedicationID
having COUNT(distinct ActiveIngredientID) = 2 -- number of ingredients

要在SQL Server中查找类似的配方,您可以执行此操作。

;with cte as 
    (   select *, COUNT(ActiveIngredientID) over (partition by MedicationID) ic from MedicationsActiveIngredients)
select t1.MedicationID, t2.MedicationID
from cte t1
    inner join cte t2
        on t1.ActiveIngredientID = t2.ActiveIngredientID
        and t1.MedicationID<>t2.MedicationID
group by t1.MedicationID, t2.MedicationID, t1.ic, t2.ic
having ABS(t1.ic-count(*))<=1 and ABS(t2.ic-COUNT(*))<=1
order by t1.MedicationID, t2.MedicationID

MySQL缺乏必要的结构,所以它会更复杂。