简体   繁体   English

将多行复制到另一张表中作为mysql中的单行

[英]Copying multiple rows into another table as a single row in mysql

I have been searching for an answer to this problem and cant find one 我一直在寻找这个问题的答案,却找不到一个

I am using my sql with Drupal on a LAMP stack 我在LAMP堆栈上将SQL与Drupal一起使用

first, if this is better in a cron job then let me know 首先,如果这在日常工作中比较好,那么请告诉我

My problem 我的问题

I have a form module that I must use. 我有一个必须使用的表单模块。 It saves the data like: 它像这样保存数据:

ID, element_id, group_id, element_value
1            0         1           Name
2            1         1        Address
3            2         1            DOB    etc...

I want to be able to take the element values and put them into 1 row in another table 我希望能够将元素值放入另一个表的1行中

so I have currently 所以我目前

INSERT INTO new_table (name, street_address,street_address_line_2, city, state, zip,
                       country, dob)
SELECT element_value 
FROM submited_table
WHERE group_id = 'some_group_id'

I am stuck as to how to place the different values in the same row to make a single record. 我对如何将不同的值放在同一行中以形成单个记录感到困惑。

Can anyone help with with this? 有人可以帮忙吗?

One way to do this is through aggregation: 一种方法是通过聚合:

INSERT INTO new_table (name, address, dob)
    SELECT max(case when element_id = 1 then element_value end) as name,
           max(case when element_id = 2 then element_value end) as address,
           max(case when element_id = 3 then element_value end) as DOB,
           . . .
    FROM submited_table
    WHERE group_id = 'some_group_id';

This assumes that element_id is identifying what each row in the first table refers to. 假定element_id正在标识第一个表中的每一行所引用的内容。 It also assumes that each element value corresponds to a column in the target table. 它还假定每个元素值都对应于目标表中的一列。

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

相关问题 MySQL查询-一个表中的单行,另一表中的多行 - MySQL query - single row in one table with multiple rows in another table 在单个表中复制mysql行 - copying mysql rows within single table MYSQL单一查询可从一个表中检索单行,也可从另一表中检索多个行作为单个字段 - MYSQL Single query to retrieve both single row from one table and many rows as a single field from another 如何在一个表中显示多行,另一个表中的一行作为单行 - How display multiple rows in a table with one row in another table as single row 将多行合并为表中的单行 - Combining multiple rows a single row in a table 加入1个表中具有单个ID /行但在另一个表中链接到多个行(相同ID)的SQL查询? - Join SQL query that has single id/row in 1 table, but links to multiple rows(same id) in another table? php + mysql:将一行从一个表复制到另一个表 - php+mysql: copying a row from one table to another MySQL在单个表中获取多行 - MySQL get multiple rows in a single table 有没有一种方法可以根据另一个表的另一行中保存的ID选择MYSQL中的多行? - Is there a way I can select multiple rows in MYSQL based on the IDs saved in another row of another table? MySQL连接,从一个表返回1行,从另一个表返回多行作为数组或列表 - MySQL join, return 1 row from one table and multiple rows from another table as an array or list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM