Question

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

Using a single query, is it possible to tell if an individual JOIN'd table was affected? For instance, given the following query, how would I know if t1 was affected and if t2 was affected?

$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();
Was it helpful?

Solution

The UPDATE_TIME column in the information_schema.tables table approximately answers the question "which table was updated". 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.

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.

OTHER TIPS

INNER JOIN ensures you only get results if a match is found on both tables.

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(); will reflect updates only on both tables.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top