Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MariaDB / MySQL Combine two tables

I have 2 tables tnHeaders and tnData

tnHeaders

fnIDX fnDESCRIPTION
1 h1
2 h2
3 h3

tnData

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

fnIDX fnHEADER_IDX fnDESCRIPTION
1 1 d1
2 1 d2
3 1 d3
4 2 d4
5 2 d5
6 2 d6
7 3 d7
8 3 d8
9 3 d9

and would like to produce this output

fnOUTPUT
h1
d1
d2
d3
h2
d4
d5
d6
h3
d7
d8
d9

I can do this in code no problem, but how can I do this in SQL? (Make the server work)

>Solution :

You need to use UNION ALL for the descriptions of both tables and sort the results in such a way that headers are on top of their data:

SELECT fnOUTPUT
FROM (
  SELECT fnDESCRIPTION fnOUTPUT, fnIDX header_index, 1 is_header FROM tnHeaders
  UNION ALL
  SELECT fnDESCRIPTION, fnHEADER_IDX, 0 FROM tnData
) t
ORDER BY header_index, is_header DESC, fnOUTPUT;

See the demo.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading