gom
gom

Reputation: 897

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

Upvotes: 0

Views: 746

Answers (2)

Federico Razzoli
Federico Razzoli

Reputation: 5391

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.

Upvotes: 1

flaschenpost
flaschenpost

Reputation: 2235

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.

Upvotes: 1

Related Questions