megaSteve4 megaSteve4 - 11 months ago 40
MySQL Question

Storing an array of id's in one db field VS breaking out into a joining table - what sql to use?

I have concluded that my first quick fix of storing an array of ids in a singular database field (1,5,48) is probably not best but if I break them out into a joining table of 'parent item id' (singular) and then sub related item id (multiple) which links to a separate table it would be better.

But now I am unsure what mysql query to use to get matches.

So a search form is submitted where "related_item" array is "1,5,8" and one of my "parent_items" has related item matches of "1" and "8" in the joining table....

So what mysql query would return these matches?


  • I have one table 'companies' maybe HSBC and TOPSHOP as example records.

  • There is a separate table of 'industries' maybe 'banking' and 'retail'

  • There is a joining table which is company_id and industry_id which pairs them both together

So if someone submits a search form for where industry = 'banking' or 'retail' how would I return the company records for 'topshop' and 'hsbc'

Answer Source

Something like this... its unclear to me form you description if you are "searching" children or parents. I think you mean to search children so:

SELECT p.*, c.* FROM child_table c
LEFT JOIN linking_table l ON ( = l.child_table_id)
LEFT JOIN parent_table p ON (l.parent_item_id =
WHERE IN (1,5,4,8)

If you mean to search parents then you can just rework the order, although you could use the exact same query with the exception that your WHERE IN clause would be on instead of

Be aware though that this will get you 1 row per match for the children so you will have the same parent multiple times. If you dont need the actual child data then you could use DISTINCT to only return one instance.