MySQL更新IF(ROW_COUNT()= 0)

Sai*_*son 3 mysql sql

我有这个SQL:

UPDATE gcd_data 
SET post_title = 'Hello World', 
    post_content = 'How Are You?',  
    post_date_gmt = '', 
    post_modified_gmt = '',
    post_url = 'www.google.com', 
    post_type = 'product'
WHERE gcd_id='1024'
IF (ROW_COUNT() = 0)
INSERT INTO gcd_data (gcd_id, post_title, post_content, post_date_gmt, 
                   post_modified_gmt, post_url, post_type) 
VALUES ('1024', 'Hello World', 'How Are You?', '', '', 'www.google.com', 'product')
Run Code Online (Sandbox Code Playgroud)

它给我这样的错误:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'IF (ROW_COUNT() = 0)
INSERT INTO gcd_data (gcd_id, post_title, post_content, pos' at line 9
Run Code Online (Sandbox Code Playgroud)

我阅读了有关IF声明的MySQL文档,但没有发现任何问题。那么,如何纠正呢?

Gor*_*off 5

我认为您应该这样做insert on duplicate key update

INSERT INTO gcd_data (gcd_id, post_title, post_content, post_date_gmt, 
                      post_modified_gmt, post_url, post_type) 
    VALUES (1024, 'Hello World', 'How Are You?', '', '', 'www.google.com', 'product')
    ON DUPLICATE KEY UPDATE 
        post_title = 'Hello World', 
        post_content = 'How Are You?',  
        post_date_gmt = '', 
        post_modified_gmt = '',
        post_url = 'www.google.com', 
        post_type = 'product';
Run Code Online (Sandbox Code Playgroud)

为此,您需要在上具有唯一索引gcd_data(gcd_id)。如果它被声明为主键(可能是),那么您将自动获得它。如果不:

create unique index idx_gcd_data_gcd_id on gcd_data(gcd_id);
Run Code Online (Sandbox Code Playgroud)

如果该字段不是唯一的,那么您应该重新考虑数据模型。

通常,多次重复这些值被认为是不好的做法。您也可以这样写:

INSERT INTO gcd_data (gcd_id, post_title, post_content, post_date_gmt, 
                      post_modified_gmt, post_url, post_type) 
    VALUES (1024, 'Hello World', 'How Are You?', '', '', 'www.google.com', 'product')
    ON DUPLICATE KEY UPDATE 
        post_title = VALUES(post_title), 
        post_content = VALUES(post_content,  
        post_date_gmt = VALUES(post_date_gmt), 
        post_modified_gmt = VALUES(post_modified_gmt),
        post_url = VALUES(post_url), 
        post_type = VALUES(post_type);
Run Code Online (Sandbox Code Playgroud)