简体   繁体   中英

Merge several columns from two tables into one rows for id in the former table each

If there are a table A and table B. The structure of them are below:

A :

id

1
2

B:

col_1    col_2

m         q
n         w

How Can I get the results of C which is below by SQL?

id     col_1   col_2    col_1  col_2 

 1       m     q        n      w
 2       m     q        n      w

For each data in Table B, they are related with the id in Table A. After concatenating the two table into Table C. once the id in Table C changes(which belongs to the id in Table A), the corresponding rows in Table C change. So in order to get the final Table C, there should be some calculations for getting each data in Table C(col_1, col_2, col_1 col_2)

As far as I understood, you want to get all rows from table B and associate as columns with id from table A.

I think it is impossible with just a query (don't know if a procedure can solve it), but I have an approach that may help (I tested it on MySQL).

SELECT 
  `a`.`id`, 
  GROUP_CONCAT(`b`.`key`) AS `keys`, 
  GROUP_CONCAT(`b`.`value`) AS `values` 
FROM `a`, `b` 
GROUP BY `a`.`id` ASC;

As result we have:

---- ------ --------
| id | keys | values |
 ---- ------ --------
|  1 | m,n  | 3,4    |
|  2 | m,n  | 3,4    |
 ---- ------ --------

The first key in column keys and first value in column values refers to the first row of table b. The second refers to the second row and so on. This way you will just need to split on the delimiter ',' with some server side code.

I searched for the matching command from Postgres to the MySQL GROUP_CONCAT and found that may do the same job. 可以完成相同的工作。

Hope it helps!

As long as you know in advance how many distinct key values can appear in B (and there are not too many), this should work:

select A.id, Once.key k1, Once.value v1, Twice.key k2, Twice.value v2
from A,(select * from B where B.key='m') Once,
(select * from B where B.key='n') Twice;

EDIT: This is the result obtained with the above query:

| ID | K1 | V1 | K2 | V2 |
--------------------------
|  1 |  m |  3 |  n |  4 |
|  2 |  m |  3 |  n |  4 |

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