简体   繁体   中英

Is it possible to insert values from one table into another AND update field values in same query?

I have two tables. One table is meant to serve as a transaction history and the other is a log of member details. When a report is run, I want to move pieces of the member details into the transaction history but ALSO update some field records which would not otherwise exist.

Is it possible to select all records which meet a specific criteria, insert only pieces of the matching row into another table AND update other fields in a single query?

For example:

In table 2, i have member name, date registered, and memberid. I want to move the above records into table 1 but also update the field (status) equal to 'processed'.

Note: I am also using php and pdo to connect to a mysql database.

Is this possible within a single query?

You didn't specify whether the rows you want to update are the same as the ones you are inserting. I am assuming they are:

insert into table1
(member_name, date_registered, memberid, status)
select member_name, date_registered, memberid, 'processed'
from table2
where SomeField = MyCriteria

After much consideration - I decided to use ircmaxell's advice and simply run multiple queries. It ends up not only making things easier but allows me to customize my sorting much easier.

As he said above, "Don't get caught in the trap of less is always better"

Yes:

SELECT *, "processed" INTO table2 FROM table1

You will have to adapt based on the table structures, perhaps even write out all the fields:

SELECT field1, field2, field3, "processed" INTO table2 FROM table1

Of note, this assumes you want to write into table 2 including the processed variable (Might I suggest a boolean?) if you want the "Processed" in the other table it will get more complicated.

Edit: Apparently mysql doesn't support select into so...

INSERT INTO table2 SELECT field1, field2, field3, "processed" FROM table1

Redfilters code works

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