vendredi 12 juin 2020

What are good design patterns for managing cross product results from a Database?

I'm looking for the more elegant way of processing result sets of a SQL query when there is a cross product. Say that I have this Scala class describing companies:

case class Company(name: String, employees: List[String])

it is the name and the list of employees. Then we have a database with tables with tables:

| id| company |      | id | employee | fk_company |
|-------------|      |----------------------------| 
| 1 | Twitter |------| 1  | bob      | 1          |
| 2 | Google  |      | 2  | sally    | 2          |
                     | 3  | fred     | 2          |

so if we want to get a list of all companies in the above representation we need have 2 alternatives:

  1. Join the tables in a query having something like:
| Twitter | bob   |
| Google  | sally |
| Google  | fred  |

but then when I get a result set that I need to split programatically, ie. collect values in the second column until there is a change in the value of the first column. It is straight forward but it feels like it will be cumbersome and error prone when the join is across several tables.

  1. I could perform several queries, first retrieve all companies and then retrieve employees for each one. Code is simpler but performance degrades.

My question is, what is the standard/most elegant design pattern for dealing with this situation?

Aucun commentaire:

Enregistrer un commentaire