简体   繁体   English

将两张表中的几列合并为前一张表中ID的一行

[英]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和表B。它们的结构如下:

A : A :

id

1
2

B: B:

col_1    col_2

m         q
n         w

How Can I get the results of C which is below by SQL? 如何获得SQL下方的C结果?

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. 对于表B中的每个数据,它们都与表A中的ID相关联。将两个表串联到表C中之后。一旦表C中的ID更改(属于表A中的ID),表C中的对应行更改。 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) 因此,为了获得最终的表C,应该进行一些计算以获取表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. 据我了解,您想从表B中获取所有行,并将其与表A中的ID关联为列。

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). 我认为仅查询是不可能的(不知道某个过程是否可以解决它),但是我有一种方法可能会有所帮助(我在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. 列键中的第一个键和列值中的第一个值引用表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 STRING_AGG may do the same job. 我搜索了从Postgres到MySQL GROUP_CONCAT的匹配命令,发现STRING_AGG可以完成相同的工作。

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: 只要您事先知道B中可以出现多少个不同的key (并且没有太多),这应该可以工作:

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 |

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

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