简体   繁体   中英

Advanced MySQL query, select, count, insert or update

So, I have a query, what it needs to do is;

  • Check if a Token exist in the sessions table
  • If not insert a token in the table
  • Else update the token in the table

SELECT COUNT(token) AS founds FROM sessions WHERE token = '" . $_SESSION['prevToken'] . "'
CASE WHEN founds == 0 THEN
    INSERT INTO sessions(token, cookie, expire)
    VALUES('" . $token . "', '', NOW() + INTERVAL 1 HOUR))
ELSE 
    UPDATE sessions SET token = '" . $token . "', expire = NOW() + INTERVAL 1 HOUR)
    WHERE  token = '" . $_SESSION['prevToken'] . "'
END CASE

But I get this error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CASE WHEN founds == 0 THEN INSE' at line 2

And I don`t know whats wrong? The CASE syntax should be right but it isn't?

You are using CASE WHEN.. as if it were a control structure. It isn't. It's used in queries. Apart from that, you can't use control structures like if or while in a query, those are only allowed in stored procedures or functions.

Also you have no delimiter after your select query.

Clément Malet's answer is right, that == is not used in MySQL.

Best solution would be indeed to useINSERT ... ON DUPLICATE KEY UPDATE like in LHristov's answer.

Apart from that, just for completeness, here's how a correct stored procedure would look like:

DELIMITER $$
CREATE PROCEDURE insert_or_update(IN p_prev_token varchar(255), IN p_token varchar(255))
BEGIN
  IF EXISTS( SELECT 1 FROM sessions WHERE token = p_prev_token ) THEN
    UPDATE sessions SET token = p_token, expire = NOW() + INTERVAL 1 HOUR)
    WHERE  token = p_prev_token;
  ELSE
    INSERT INTO sessions(token, cookie, expire)
    VALUES(p_token, '', NOW() + INTERVAL 1 HOUR));
  END IF;
END $$
DELIMITER ;

You would then call it with something like this (I'm no PHP programmer, therefore I don't know how to escape the variables or whatever):

CALL insert_or_update($_SESSION['prevToken'], $token);

PS: And in general don't COUNT() when all you need to know is, if there's an entry. EXISTS() stops as soon as the first entry is found, whereas COUNT() continues to scan the table.

So you need INSERT ... ON DUPLICATE KEY UPDATE . Get some info fromdocumentation

You can't use '==' in MySQL.

Replace WHEN founds == 0 with WHEN founds = 0

you also can use

ON DUPLICATE KEY UPDATE

and not use case. ex:

INSERT INTO table (a,b,c) VALUES (1,2,3)
  ON DUPLICATE KEY UPDATE c=c+1;

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