[英]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.