سؤال

I have multiple tables with relationships. sometimes I need to do a join just to check if status = true and the query is large and a little confusing ...

wanted to know how to approach this type of situation in large projects.

was thinking of creating a table with parent and status to group all conditions - in this case only need a simple query to check if the relationship status of this true or false.

like this:

select *
from table
where table.parent in (select id from tableB where status = 1)
   or table.parent in (select id from tableC where status = 1)
   or table.parent in (select id from tableD where status = 1)

this is a good approach? never tested and do not know to what extent it can be the best solution

thank you

هل كانت مفيدة؟

المحلول

I am little confused. Do you want to redesign your data structure, or want to optimize your query?

Without clear specification I can't offer optimized data structure. Though here is some optimization suggestion based on some assumptions.

  • If your parent id do not overlapped between the tables(i.e. tableb, tablec, tabled do not have common id) You can move status field to your 'table' table.
  • If they share some id then previous would not work. then you can use Denormalization. Add status field to the 'table' table, and keep it up to date while any of the status changed.

If you like to keep your data structure then you can optimize your query by removing sub-queries and using join instead.

In most cases JOINs are faster than sub-queries and it is very rare for a sub-query to be faster.

In JOINs RDBMS can create an execution plan that is better for your query and can predict what data should be loaded to be processed and save time, unlike the sub-query where it will run all the queries and load all their data to do the processing.

The good thing in sub-queries is that they are more readable than JOINs: that's why most new SQL people prefer them; it is the easy way; but when it comes to performance, JOINS are better in most cases even though they are not hard to read too.

نصائح أخرى

You really haven't given much information - or even asked a clear question :(

SUGGESTIONS:

1) Focus on your data design first

2) Make sure your design allows the querying whatever you need from the data. For example, if you need to check "status" by date, then make sure you have datetime columns.

3) "Optimizing" queries comes later in the game. Make sure your queries are correct first, worry about "optimization" later.

4) Tuning your database (for example, identifying and implementing indexes) is crucial, and should always be done in conjunction with 3)

'Hope that helps!

PS:

If you have a specfic question, please be sure to show some sample code.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top