Skip to content
Advertisement

Is LEFT JOINING two tables with no reference to each other ON string conditions a bad idea?

I’m migrating database between 2 systems using PHP and MySQL.

In the old one I have 3 tables of interest:

t1
id (int)

t2
id (int)
t1_id (int)
d (string)

t3
id (int)
t1_id (int)
ds (string)
e (int)

In the new one I have only t1 and t2

t2.d can have e.g. “abc” or “def” t3.ds can have “abc” or “def” or “abc, def”

I have created the following query:

JavaScript

The query does work, but I am worried about the performance of this JOIN when I have lots of entries (to migrate I obviously iterate over each of the entries from t1, each having multiple entries in t2 and t3).

So at the bottom, I go back to the question – is it worth to join them like that or should I use a different approach, like separate query or data manipulation on PHP level?

Here’s MySQL EXPLAIN if that’s any relevant (unfortunately it doesn’t mean too much to me, so I appreciate any help):

JavaScript

Advertisement

Answer

If you are concerned about performance, then do not store lists in a string. You should have a junction table, with one row per element of the list. In other words, 'abc, def' is a no-no. Another table with two rows, one for 'abc' and another for 'def' is the way to go.

Because you have a data structure that is not optimized for SQL, there is little you can do from a performance perspective. The like is probably about as good as you can do.

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