简体   繁体   English

数据库左外部连接到具有最佳性能的Same表

[英]Database left outer join to with Same table with optimal performance

I have a status table A with Code & its description related to a particular name. 我有一个状态表A,其中包含代码及其与特定名称有关的描述。

Code   Desc       Name
 01    INITIAL   STATUS_A
 02    SUCCESS   STATUS_A
 03    FAILED    STATUS_A
 04    FAILED    STATUS_B
 05    RETRY     STATUS_C
 06    SUCESS    STATUS_D

and so on... Now I have a table B as master record with code associate from Table A. 依此类推...现在,我将表B作为主记录,并将代码与表A关联。

ID  column1 column2 column3 statusA statusB statusC statusD 
432   XXXX   YYYY    ZZZZ      03     04      05      06      

Now I need to form a query to get output data with code description from table A. 现在,我需要构成一个查询,以从表A中获取带有代码描述的输出数据。

I have done this using left outer join. 我已经使用左外部联接完成了此操作。 Can someone suggest a better solution. 有人可以提出更好的解决方案。

Left Outer Join Query 左外连接查询

Select b.column1 ,b.column2, a1.Desc as Status_A_Desc , a2.Desc as Status_B_Desc, a3.Desc as Status_C_Desc, a4.Desc as Status_D_Desc from B b left outer join A a1 on a1.code = b.statusA and a1.Name ='STATUS_A' left outer join A a2 on a2.code = b.statusB and a2.Name ='STATUS_B' left outer join A a3 on a3.code = b.statusC and a3.Name ='STATUS_C' left outer join A a4 on a4.code = b.statusD and a4.Name ='STATUS_D' where b.ID = 432

You can use conditional aggregation instead: 您可以改为使用条件聚合:

select a.code,
       max(case when a.name = 'Status_A' then a.desc end) as a,
       max(case when a.name = 'Status_B' then a.desc end) as b,
       max(case when a.name = 'Status_C' then a.desc end) as c,
       max(case when a.name = 'Status_D' then a.desc end) as d
from a
group by a.code;

Depending on your database, the joins might be better. 根据您的数据库,联接可能会更好。 This has the advantage that you can add as many fields as you like with basically the same performance. 这样做的好处是,您可以添加任意数量的字段,并且性能基本相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM