简体   繁体   English

确定SQL UPDATE是否影响单个JOINed表

[英]Determine if SQL UPDATE affected individual JOINed tables

According to http://us3.php.net/manual/en/pdostatement.rowcount.php : 根据http://us3.php.net/manual/en/pdostatement.rowcount.php

PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object. PDOStatement :: rowCount()返回受相应PDOStatement对象执行的最后一个DELETE,INSERT或UPDATE语句影响的行数。

Using a single query, is it possible to tell if an individual JOIN'd table was affected? 使用单个查询,可以判断单个JOIN表是否受到影响? For instance, given the following query, how would I know if t1 was affected and if t2 was affected? 例如,给定以下查询,我如何知道t1是否受到影响以及t2是否受到影响?

$sql ='UPDATE t1 INNER JOIN t2 ON t2.t1_id=t1.id SET t1.foo=:foo, t2.bar=:bar WHERE t2.id=:id';
$stmt = db::db()->prepare($sql);
$stmt->execute(array('foo'=>123,'bar'=>321,'id'=>10));
$rows_t1=$stmt->rowCount();
$rows_t2=$stmt->rowCount();

INNER JOIN ensures you only get results if a match is found on both tables. INNER JOIN确保只有在两个表上都找到匹配项时才能得到结果。

Which means if the database can not match a result in one of the tables then the row is not included in the result set. 这意味着,如果数据库无法匹配表之一中的结果,则该行不包含在结果集中。

So the number of results returned from stmt->rowCount(); 因此,从stmt->rowCount();返回的结果数stmt->rowCount(); will reflect updates only on both tables. 将仅在两个表上反映更新。

The UPDATE_TIME column in the information_schema.tables table approximately answers the question "which table was updated". information_schema.tables表中的UPDATE_TIME大致回答了“哪个表已更新”的问题。 Basic example: 基本示例:

SELECT UPDATE_TIME
  FROM information_schema.tables
 WHERE TABLE_SCHEMA = 'database' AND TABLE_NAME = 'table'

If you were to run this right after your modifying statements, you could limit to a window of a few seconds to check if a particular table was updated, like: 如果要在修改语句后立即运行此命令,则可以限制在几秒钟的时间里检查特定表是否已更新,例如:

SELECT COUNT(*)
  FROM information_schema.tables
 WHERE TABLE_SCHEMA = 'database' AND TABLE_NAME = 'table'
   AND UPDATE_TIME BETWEEN (NOW() - INTERVAL 30 SECOND) AND NOW();           

which returns 1 if that table was updated in the last 30 seconds, or 0 if not. 如果该表在最近30秒内已更新,则返回1,否则返回0。

I stress this is an approximate answer, because a query other than the one you last executed might have affected that table. 我强调这是一个大概的答案,因为除您上次执行的查询以外的查询可能已经影响了该表。 If you were to wrap this in a transaction or a lock, then you could use this to actually answer your question: with the cost of write-locking other connections. 如果要将其包装在事务或锁中,则可以使用它来实际回答您的问题:以写锁定其他连接为代价。

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

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