简体   繁体   中英

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. 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.

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 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.

???

Anyone know what I need to do in order to make this work?

It sounds like you don't really want an UPDATE statement. After you run an UPDATE , your table still has the same number of records as before; 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;

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