0

I couldn't decide on my data model for the performance and easiness of use perspectives or if I need to consider any other thing. The application will be Spring service and it will be a relational DB.

Two design comparison

SELECT * from MainTable mt;
left join TableA ta
left join TableB tb
left join TableC tc
where (mt.startDate <= givenStartDate and mt.endDate => givenEndDate)
AND (ta.aId IN givenAIds or tb.bId IN givenBIds OR tc.cId IN givenCIds)

VS

SELECT * from MainTable mt;
left join TableCommon tableCommon;
where (mt.startDate <= givenStartDate and mt.endDate => givenEndDate)
AND tableCommon.fkId = mt.id
AND ( (tableCommon.tableType = "A" and tableCommon.tableId IN givenAIds) 
  OR (tableCommon.tableType = "B" and tableCommon.tableId IN givenBIds)
  OR (tableCommon.tableType = "C" and tableCommon.tableId IN givenCIds)
  )

One or more filters might be added from the main table.

We will use bIds to fetch details of B from another service after we fetch the result of the query.

I have different filter scenarios for fetching data between specific time intervals.

argmnt
  • 69
  • 6
  • 1
    Because of the WHERE conditions all your LEFT JOINs turn into INNER JOINs. A query with just 3 joins would be one of the smaller and easier ones we have, and none of our complex queries has a performance issue. Response times around one millisecond on a couple of billion records. Data model, indexes, data, SQL, that makes the difference. Not just the number of joins – Frank Heikens Mar 09 '23 at 12:55
  • 1
    Does this answer your question? [How to design a product table for many kinds of product where each product has many parameters](https://stackoverflow.com/questions/695752/how-to-design-a-product-table-for-many-kinds-of-product-where-each-product-has-m) – Shadow Mar 09 '23 at 13:00
  • See [How do comment replies work?](https://meta.stackexchange.com/q/43019/266284) to learn to use `@x` to notify 1 non-sole non-poster commenter `x` per comment about that comment. Posters, sole commenters & followers of posts always get notified. Without `@` other commenters get no notification. PS Please don't insert "EDIT"s/"UPDATE"s, just make your post the best presentation as of edit time. [ask] [Help] – philipxy Mar 10 '23 at 04:48
  • [Why should I not upload images of code/data/errors when asking a question?](https://meta.stackoverflow.com/q/285551/3404097) An ERD is an image of DDL. – philipxy Mar 10 '23 at 04:49
  • There is no question in this post. PS [Strategy for “Which is better” questions](https://meta.stackexchange.com/q/204461) [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/q/261592/3404097) – philipxy Mar 10 '23 at 04:55

1 Answers1

0

I am no db expert but one join would be faster imo.

However, your second query should use OR otherwise it won't return any result.

destan
  • 4,301
  • 3
  • 35
  • 62