I would like to print a list of items from a database table, and together with each one, a little list (10 items max) of related subitems.
For example, I have these 2 tables:
ITEMS
id: integer
name: string
SUBITEMS
id: integer
name: string
item_id: integer
So, an item can have many subitems.
I would like to print something like this:
Item 1
this item has: subitem 1, subitem 2, subitem 3
Item 2
this item has: subitem 4, subitem 5, subitem 6
Item 3
this item has: subitem 2, subitem 4, subitem 7
How could I get this with performance in mind? As I said, each item can have many subitems, but I’ll be showing a maximum of 10.
If I make a select with a join, I think it could stress too much the database when there is a pagination of, for example, 25 items per page, and 100 users querying. So, I think this would not be a good solution.
I have thought about a workaround, something dirty: adding a new field to the ITEMS table, named subitems_summary (of type text), and each time a subitem is assigned to an item, I make the select to join the two tables, and store there the results, so I can format the data from that field later on. For example, in the listing above, the subitems_summary field for Item 3 would be: “subitem 2; subitem 4; subitem 7”.
What do you think?
Since I’m not getting more answers I’ll post my opinion.
As Oleksi says, the DBMS is good enough to run joined queries. This can be true with a low quantity of visitors. But keeping an eye on scaling, this would not be an optimized way to do complex things.
I think there are interesting techniques that I would love to read, but I’m more towards optimizing queries from the start, at least a little. In my opinion it’s not a good idea to use joins deliberately. In professional sites it’s better to duplicate fields just for that reason.
Anyway, to achieve what I was asking, I would do this: https://stackoverflow.com/a/11301759/267705