Remember a sql union usage scenario record

I guess this blog can only be understood by myself. It involves many specific business attributes that cannot be explained. It is used as a record of my own processing.

Recently, during a development, I worked on a problem for three days, and finally solved it by using union in SQL.

The detailed scenario cannot be explained. Here is a brief description of the approximate usage scenario. The problem scenario is a data synchronization problem in three databases.

Database A is the initial data, and the business data has a data frequency, as well as another attribute Buuid and Cuuid, D

B and C are many-to-many relationships, and D and C are one-to-many relationships.

But each C must have a frequency attribute.

There is TBL_C_FREQUENCY in synchronizing data from database A to database A1, and the frequency attributes corresponding to each C attribute are relatively complete.

When synchronizing data from database A and A1 to database A2, there are data tables TBL_B_C and TBL_D_C,

The data in TBL_D_C in the database is relatively redundant, but the data between data B and C in database TBL_B_C is missing.

What was used in the original sql was

The results obtained by TBL_D_C INNER JOIN TBL_B_C have errors because TBL_B_C is missing some data.

The initial modification was made using LEFT JOIN.

Some of the special scenarios where the problem lay were solved, but data redundancy was found when using the full scenario. I have been dealing with this issue for a long time, and my thinking has always been that I cannot use LEFT JOIN. I can only think about synchronizing A2 from database A and A1. This is a huge workload.

Later I found that if B is not in TBL_D_C, then the BUUID field is empty'', if there is one, it is the specific BUUID.

So the key statement uses union connection

SELECT * FROM 

TBL_D_C

LEFT JOIN 

TBL_B_C

ON

TBL_D_C.CUUID = TBL_B_C.CUUID 

WHERE TBL_D_C.BUUID != '' 

UNION 

SELECT 

TBL_D_C  WHERE TBL_D_C.BUUID = ''  

Perfect problem solving.

 

Guess you like

Origin blog.csdn.net/harryptter/article/details/118073618