简体   繁体   中英

MySQL to select or insert based on condition

How to do this in a single MySQL query:

if (select count(*)..)=10
  select a record from the same table
else
  insert a record into the same table

As long as only one webserver is involved, I would try APC http://php.net/manual/de/book.apc.php with some nice system of timeout.

Say for example: if an IP has already sent a request in the last 2 seconds, it's current request should be refused and the timeout changes to 4 seconds, after that 10 seconds etc.

if ($timeoutLevel = apc_fetch("locked_" . $ip)){
    $timeoutLevel++;
    $timeout = getNextTimeout($timeoutLevel);
    apc_store("locked_".$ip, $timeoutLevel, $timeout);
    show_my_error_page(get_friendly_text("please do not try again for $timeout seconds! You are Blocked!"));
    exit();
}
else{
    $timeoutLevel = 1;
    $timeout = INITIAL_PAGE_TIMEOUT;
    apc_store("locked_".$ip, $timeoutLevel, $timeout);
}

That should cost at max around 50 Byte per ip of the last x seconds, so if it is not a DDOS then the webserver should have that RAM.

But be careful: some html-pages contain references to css, javascript, images, sounds, ajax-calls might come later, json-requests etc. pp.

After $timeout seconds APC automatically drops that value, so no need to hire a cleaning women.

If you want to use one single SQL command (but I don't know why) you can use a Stored Procedure:

CREATE PROCEDURE `select_or_insert`()
    MODIFIES SQL DATA
    COMMENT 'blah blah'
BEGIN
    IF ((SELECT COUNT(*) FROM `your_table`) = 10) THEN
        SELECT ... FROM ... ;
    ELSE
        INSERT INTO ... ;
    END IF;
END;

To invoke the Procedure you will issue the following command:

CALL `select_or_insert`();

If the SELECT is executed, the statement will return a resultset.

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