We help IT Professionals succeed at work.
Get Started

Join 3 MySQL Tables Together

Last Modified: 2012-05-11

I have a very large database I am dealing with and am having trouble getting results in a single query for 3 database tables.

I attached a code snippet of these 3 tables with sample data.

What I need to do is this:

1. Loop through zSS_ndc_medid
2. JOIN zSS_ndc_medid to RM_MEDID using NDC
3. For each row in zSS_ndc_medid take the NDC from that row and search through zSS_formulary_list for this NDC. However, results must be limited to any row that has a value of provider=RXHUBPBM and List_ID=FSL101 (results wont always be found as there wont always be the NDC from this row in the zSS_formulary_list table).

Currently I have no problem with number 1 or 2. I can properly JOIN the two tables based on NDC and display results. But when I want to search through zSS_formulary_list I have to create another query inside of a loop which is really slow. Is there a way to combine all this in to a single query?

If it's impossible to do this in a single query are there any other optimization tips I can get? I can not change the format of this data, but I can add additional tables.

Help would be much appreciated. Thank you!


1001	|11	|2
1002	|11	|2
1003	|11	|3
1004	|11	|2
1005	|13	|2
1006	|16	|2


NDC		|List_ID	|Provider	|Status		
1001		|FSL101		|RXHUBPBM	|2
1002		|FSL101		|RXHUBPBM	|2
1003		|FSL101		|RXHUBPBM	|5
1004		|FSL101		|RXHUBPBM	|2
1001		|FSL102		|RXHUBPBM	|2
1002		|FSL102		|RXHUBPBM	|2
1003		|FSL103		|RXHUBPBM	|5
1004		|FSL104		|RXHUBPBM	|2


MED_ID		|Name		|
11		|One		|
13		|Two		|
16		|Three		|

Open in new window

Watch Question
Chief Technology Officer
Most Valuable Expert 2011
This problem has been solved!
Unlock 3 Answers and 6 Comments.
See Answers
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE