I am trying to build a query for later inserting it in a table I'm building. I want the query to return 4 columns, which are 4 ids from different entities which relate with each other. I've got one table with the relations, but with varchars, and four tables where I already put the different occurences with an ID each:
TABLE RELATIONS:
A B C D
Sony Bravia 32" 1200€
JVC Whatever 15cm 200€
Samsung Galaxy 13" 500€
TABLE A:
id name
1 Sony
2 JVC
3 Samsung
TABLE B:
id name
1 Whatever
2 Galaxy
3 Bravia
TABLE C:
id name
1 13"
2 15cm
3 32"
TABLE D:
id name
1 200€
2 1200€
3 500€
Now, what I want to get with my query is:
QUERY RESULT:
A B C D
1 3 3 2
2 1 2 1
3 2 1 3
Firstly, I constructed this one:
SELECT DISTINCT A.id as A, B.id as B, C.id as C, D.id as D
FROM relations
INNER JOIN A ON A.name = relations.A
INNER JOIN B ON B.name = relations.B
INNER JOIN C ON C.name = relations.C
INNER JOIN D ON D.name = relations.D
It seems correct, but it takes sooooo long (maybe hours) to complete. The table sizes are (80,65000,1900,15) for the 4 entities, and 65000 for the relations table.
If I perform just one of the joins it takes 15ms, if I perform two of them 6-7 seconds, and with 3 o 4 the time increases exponentially. I think maybe the JOIN solution might be overkill for my situation, as I only need to "translate" the strings...
I already created an index for every "name" field in the four entity tables, as well as an index for relations.a,.b,.c,.d.
Curiously, it takes almost nothing if what I do is duplicate the a,b,c,d columns in the relations table and perform 4 UPDATE queries inserting the id into the duplicate field, matching its "parent"...but I'm sure there's gotta be a better way to do that...anyone has an idea?
Many thanks! EXPLAIN result http://www.redlanemedia.com/explain.png