2

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.

vagabondtechie
  • 213
  • 2
  • 8
  • Are you saying that you dont want to include 2 even though it has the same generices, and 'Hexachlorodine' even has the same potency, because the generic of 'Methyl Benzoate' has a different potency? – Steve Sep 26 '13 at 19:28
  • @Steve Yes. Because two medicines would be equivalent only when they match on having exact same generics and exact same potency. – vagabondtechie Sep 27 '13 at 02:55

1 Answers1

2

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

peterm
  • 91,357
  • 15
  • 148
  • 157