Skip to content
Advertisement

How to retrieve data from two MySQL tables with multiple associations

I got these two tables where one table is having multiple foreign keys to the second table.

Table rankings

Table item

One ranking record may have multiple association to item table using first_item_id, second_item_id, third_item_id or forth_item_id fields. I want to retrieve ranking records with the corresponding item_code instead of the item.id. What would be the most efficient way to do this if i have a big number of data?

PS: There are 10 associations to the item.id as first_item_idtenth_item_id. Im using Rails ActiveRecord ORM. Any workaround with that also fine.

Sample data ranking

SELECT id,search_text,first_item_id as first,second_item_id as second,third_item_id as third,forth_item_id as forth from rankings limit 10;

Sample item data

SELECT id,item_code from items limit 5;

Expected data

Advertisement

Answer

Joining the table multiple times (even many, many times) should not be a problem, as you are joining on the primary key, i.e. you have an index that will be used.

I am using outer joins here, because all your item columns are nullable.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement