Merge multiple query results into one column in MySQL/MariaDB

Source: Internet
Author: User

Recently, a query requirement is how to display a column when multiple select columns -- for example, if the table contains three columns and two rows:

1 2 3
4 5 6
How to convert query results into one column and multiple rows:

1
2
3
4
5
6
First, create a test table.

Create table test (c1 int, c2 int, c3 int );
Insert into test values (, 3), (, 6), (, 9), (, 12 );

 

Method 1: Use union

Select c1 from test union select c2 from test union select c3 from test;

 

This method is the easiest to understand, that is, to query three times, one column at a time, and then merge; but the disadvantage is to scan the table three times.

Method 2: insert a line break

Mysql-Bse "select concat (c1, '@', c2, '@', c3) from test;" | sed's/@/\ n/g'

 

This method is also easy to understand. Line breaks are inserted between fields. Compared with the first method, you only need to access the table once. The disadvantage is that you need to use an external text processing tool.

Method 3: Use case

Select case when rownum = 1 then c1 when rownum = 2 then c2 when rownum = 3 then c3 else ''end from test, (SELECT @ rownum: = @ rownum + 1 AS rownum FROM (SELECT @ rownum: = 0) r, test) B;

 

This method is intended by my colleague shengkaisu. It is hard to understand: generate row number rownum, and then generate the row number table and old table for Cartesian product. If rownum is 1, select the first column, if rownum is 2, select the second column ...........

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.