简体   繁体   中英

SQL: querying multi-level hierarchical tables

I'm currently trying to create a multi-level structure from different tables There are many steps for a test. The underlying relationship is:

1. parent sequence AA
 1.1 child sequence BB
  1.1.1 Step CC 

There are three tables:

result_uut has the following columns:

uut_id, uut_serial_number, uut_name

result_seq has

uut_id, step_id, step_parent_id, step_name

result_uut and result_seq is linked by uut_id the parent-child relationship is reflected by step_id = step_parent_id

result_step has

uut_id, step_id, step_parent_id, step_name

It is linked to result_seq by result_seq.step_id = result_step.step_parent_id

I wonder how to let the output have parent seq name, child seq name, and step name, and display in order (1->1.1->1.1.1->1.1.2...) .

Not tested, I hope I got this right, but if not at least you get the idea (the assumption is that you are working with 32 bit ints for uut_id):

select cmb.tag from (select uut_id as tag,concat(lpad(uut_id,10,'0'),repeat('0',20)) as ord or from result_uut 
union
select concat_ws('.',aa.uut_id,bb.uut_id,cc.uut_id) as tag,concat(lpad(aa.uut_id,10,'0'),lpad(bb.uut_id,10,'0'),repeat('0',10)) as ord from result_uut aa join result_seq bb on aa.uut_id = bb.step_parent_uut_id
union
select concat_ws('.',aa.uut_id,bb.uut_id,cc.uut_id) as tag,concat(lpad(aa.uut_id,10,'0'),lpad(bb.uut_id,10,'0'),lpad(cc.uut_id,10,'0') as ord from result_uut aa join result_seq bb on aa.uut_id = bb.step_parent_uut_id join result_step cc on bb.uut_id = cc.step_parent_uut_id) cmb order by ord;

The idea is that we use joins to generate the tags, with each tag we generate the ord token that is a 30 digit integer obtained by concatenation of the uut_ids each padded to 10 digits. This hack is necessary because if we just tried to build the actual integer we would overflow 64 bits. Then we union, order by ord and throw away the ord with the help of a simple sub-query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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