简体   繁体   中英

Execute insert query, only if count rows equals x

$res = $db->query("SELECT COUNT(*) as cnt FROM table")->fetchAll(PDO::FETCH_ASSOC);
if ( $res[0]['cnt'] == 0 ) {

   $db->query("
   INSERT INTO table (col) 
   VALUES
   ('value1'),
   ('value2'),
   ('value3'),
   ....
   ");

}

Suppose 2 users requested this code same time,

So, for first user, count will return 0 and INSERT query will executed, but there is possible that while first insert executed, for second user, count return also 0 ? (and in this case second insert query will also executed, what I don't need).

If this is possible, how to prevent this? Using Transactions will help in such cases ?

So, you want to insert only if there are no records in the table. Transactions won't help you.

You can use a WRITE LOCK:

Only the session that holds the lock can access the table. No other session can access it until the lock is released.

https://dev.mysql.com/doc/refman/5.0/en/lock-tables.html

Use the following method:

mysql> LOCK TABLES t1 WRITE;

mysql> SELECT COUNT(*) FROM t1;

mysql> INSERT INTO t1 (col) 
   VALUES
   ('value1'),
   ('value2'),
   ('value3');

mysql> UNLOCK TABLES;

If another session tries to execute the command LOCK TABLES t1 WRITE; , it will wait until the first session finishes. So COUNT will always return the correct value.

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