简体   繁体   English

MySQL插入表1更新表2,子查询或事务?

[英]MySQL insert table1 update table2, subquery or transaction?

I want to insert or update, then insert a new log into another table. 我要插入或更新,然后将新日志插入另一个表。

I'm running a nifty little query to pull information from a staging table into other tables, something like 我正在运行一个漂亮的小查询,以将信息从临时表中拉到其他表中,例如

Insert into select on duplicate key update 插入到选择重复密钥更新中

What I'd like to do without php, or triggers (the lead dev doesn't like em, and I'm not that familiar with them either) is insert a new record into a logging table. 我想在没有php或触发器的情况下要做的事情(首席开发人员不喜欢em,而且我也不熟悉它们)是在记录表中插入一条新记录。 Needed for reporting on what data was updated or inserted and on what table. 需要报告更新或插入了哪些数据以及在什么表上。

Any hints or examples? 有任何提示或示例吗?

Note: I was doing this with php just fine, although it was taking about 4 hours to process on 50K rows. 注意:我用php做得很好,尽管要处理5万行大约需要4个小时。 Using the laravel php framework, looping over each entry in staging update 4 other tables with the data and log for each one was equalling 8 queries for each row (this was using laravel models not raw sql). 使用laravel php框架,在暂存中更新每个其他表的每个条目,并更新每个表的数据和日志等于每行8个查询(这是使用laravel模型而不是原始sql)。 I was able to optimise by pushing logs into an array and batch processing. 我能够通过将日志推送到数组中并进行批处理来进行优化。 But you can't beat 15sec processing time in mysql by bypassing all that throughput. 但是通过绕过所有吞吐量,您无法在mysql中超过15秒的处理时间。 Now I'm hooked on doing awesome things the sql way. 现在,我迷上了以sql方式做很棒的事情。

If you need executing more than one query statement. 如果您需要执行多个查询语句。 I refer to use transaction then trigger to guarantee Atomicity (part of ACID ). 我指的是使用事务,然后触发以确保原子性ACID的一部分)。 Bellow code is sample for MySql transaction : 波纹管代码是MySql事务的示例:

START TRANSACTION;
UPDATE ...
INSERT ...
DELETE ...
Other query statement
COMMIT;

Statements inside transaction will be executed all or nothing. 事务内的语句将全部执行或不执行。

If you want to do two things (insert the base row and insert a log row), you'll need two statements. 如果您想做两件事(插入基本行并插入日志行),则需要两个语句。 The second can (and should) be a trigger. 第二个可以(并且应该)是触发器。

最好使用触发器,它通常用于记录目的

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

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