SQL Query for exact match in many to many relation

六眼飞鱼酱① 提交于 2019-12-22 12:50:09

问题


I have the following tables(only listing the required attributes)

  1. medicine (id, name),
  2. generic (id, name),
  3. med_gen (med_id references medicine(id),gen_id references generic(id), potency)

Sample Data

medicine

  1. (1, 'Crocin')
  2. (2, 'Stamlo')
  3. (3, 'NT Kuf')

generic

  1. (1, 'Hexachlorodine')
  2. (2, 'Methyl Benzoate')

med_gen

  1. (1, 1, '100mg')
  2. (1, 2, '50ml')
  3. (2, 1, '100mg')
  4. (2, 2, '60ml')
  5. (3, 1, '100mg')
  6. (3, 2, '50ml')

I want all the medicines which are equivalent to a given medicine. Those medicines are equivalent to each other that have same generic as well as same potency. In the above sample data, all the three have same generics, but only 1 and three also have same potency for the corresponding generics. So 1 and 3 are equivalent medicines.

I want to find out equivalent medicines given a medicine id.

NOTE : One medicine may have any number of generics. Medicine table has around 102000 records, generic table around 2200 and potency table around 200000 records. So performance is a key point.

NOTE 2 : The database used in MySQL.


回答1:


One way to do it in MySQL is to leverage GROUP_CONCAT() function

SELECT g.med_id
  FROM 
(
  SELECT med_id, GROUP_CONCAT(gen_id ORDER BY gen_id) gen_id, GROUP_CONCAT(potency ORDER BY potency) potency
    FROM med_gen
   WHERE med_id = 1 -- here 1 is med_id for which you're trying to find analogs
) o JOIN 
(
  SELECT med_id, GROUP_CONCAT(gen_id ORDER BY gen_id) gen_id, GROUP_CONCAT(potency ORDER BY potency) potency
    FROM med_gen
   WHERE med_id <> 1 -- here 1 is med_id for which you're trying to find analogs
   GROUP BY med_id 
) g
 ON o.gen_id = g.gen_id
AND o.potency = g.potency

Output:

| MED_ID |
|--------|
|      3 |

Here is SQLFiddle demo



来源:https://stackoverflow.com/questions/19036165/sql-query-for-exact-match-in-many-to-many-relation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!