简体   繁体   English

在同一表中使用带有GROUP_CONCAT的SELECT语句进行UPDATE

[英]Doing UPDATE using a SELECT statement with GROUP_CONCAT within the same table

I'm trying to update a database table within MySQL to combine rows. 我正在尝试更新MySQL中的数据库表以合并行。 Here's what part of the table looks like: 表格的一部分如下所示:

NID     SID     CID     NO      DATA  
5297    32002   5   0   10  
5297    32002   5   1   17  
5297    32002   5   2   1976

The 'DATA' column contains the month, day, and year that make up a date. “数据”列包含组成日期的月份,日期和年份。 So I would like to combine those records into the following: 因此,我想将这些记录合并为以下内容:

5297    32002   5   0   10-17-1976

For each SID, it contains a CID with 3 different rows, indicated by the 'No' column and containing the three parts of the date. 对于每个SID,它包含一个具有3个不同行的CID,由“否”列指示,并包含日期的三个部分。

I can get the output desired with this select statement: 我可以通过以下选择语句获得所需的输出:

SELECT GROUP_CONCAT( d.data ORDER BY `no` SEPARATOR '-') AS data FROM
webform_submitted_data_copy d WHERE cid = "5" GROUP BY d.sid

This returns what is desired to be in the 'data' column following an UPDATE..but I can't figure out how to form the correct UPDATE statement... Something like: 这将返回在UPDATE之后的“数据”列中所需要的内容。但是我无法弄清楚如何形成正确的UPDATE语句……类似:

UPDATE webform_submitted_data_copy 
SET webform_submitted_data_copy.data = (GROUP_CONCAT( d.data ORDER BY `no` SEPARATOR '-'))
WHERE webform_submitted_data_copy.cid = "5" GROUP BY webform_submitted_data_copy.sid

But this affects 0 rows, and has no failures...tried many other possible statements with no joy. 但这会影响0行,并且没有失败...尝试了许多其他可能的语句而没有喜悦。

??? ???

Anyone know what I need to do in order to make this work? 有人知道我需要做些什么才能使这项工作吗?

It sounds like you don't really want an UPDATE statement. 听起来您真的不想要UPDATE语句。 After you run an UPDATE , your table still has the same number of records as before; 运行UPDATE ,您的表仍具有与以前相同的记录数; but it sounds like you want it to end up with one-third as many records as it started with. 但是听起来好像您希望它最终获得的记录数量是开始时的三分之一。 (Right?) (对?)

So I think your best bet is to create a temporary table; 因此,我认为您最好的选择是创建一个临时表。 something like this: 像这样的东西:

CREATE TABLE webform_submitted_data_copy_temp
SELECT d.nid, d.sid, d.cid, GROUP_CONCAT( d.data ORDER BY `no` SEPARATOR '-') AS data FROM
webform_submitted_data_copy d WHERE cid = "5" GROUP BY d.sid;

UPDATE webform_submitted_data_copy
   SET data =
        ( SELECT data
            FROM webform_submitted_data_copy_temp
           WHERE sid = webform_submitted_data_copy.sid
        )
 WHERE cid = '5'
   AND no = 0
;

DELETE webform_submitted_data_copy
 WHERE cid = '5'
   AND no > 0
;

DROP TABLE webform_submitted_data_copy_temp;

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

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