简体   繁体   中英

INSERT INTO WITH SELECT resulting in multiple rows inserted instead of just one

INSERT INTO `mailinglist_archives`
              (`recipients`) 
               SELECT `email`
               FROM mailinglist

SQL RESULT:

row 1 - xxxx@gmail.com

row 2 - sss@gmail.com

row 3 - abc@gmail.com

row 4 - orange@gmail.com

What i need -

row 1 - xxxx@gmail.com,sss@gmail.com,abc@gmail.com,orange@gmail.com

Try like this

INSERT INTO `mailinglist_archives`
              (`recipients`) 
               SELECT GROUP_CONCAT(`email`)
               FROM mailinglist

You can do this with GROUP_CONCAT :

INSERT INTO `mailinglist_archives`
          (`recipients`) 
           SELECT GROUP_CONCAT(`email`)
           FROM mailinglist

That said, this is not a good idea; you should normalize your database, rather than storing lists in columns.

Edit to address comment:

You can combine these two queries:

$query0 = "INSERT INTO mailinglist_archives (subject, message, datesent) VALUES ('$subject', '$ckcontent', '$timestamp')";
$query01 = "INSERT INTO mailinglist_archives (recipients) SELECT GROUP_CONCAT(email) FROM mailinglist";

like this:

INSERT INTO mailinglist_archives (subject, message, datesent, recipients)
SELECT '$subject', '$ckcontent', '$timestamp', GROUP_CONCAT(email) FROM mailinglist

Again, however, this will result in a (potentially very large) list in the recipients column. This will cause problems, sooner or later, so you are better off normalizing the data by creating a new table to match recipient ids and message ids.

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