简体   繁体   中英

MySQL Where Not Exists Insert Record based on 3 values

I have a need to do an insert to MySQL where a record does not exist in the destination table already

my query

INSERT INTO comment (`mid`, `pid`, `comment_text`, `comment_date`, `comment_type`) 
 VALUES (180, 2, NULL, '2012-07-26 10:19:00', 'tag')  WHERE NOT EXISTS ( SELECT * FROM `comment` WHERE `mid`=180 AND `pid`=2 AND `comment_type`='tag')

however when this runs 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 'WHERE NOT EXISTS ( SELECT * FROM comment WHERE mid =180 AND `pid' at line 2

Any ideas essentially i want to stop duplicate rows being added to this table when they match the values

try:

INSERT IGNORE INTO comment
(
 `mid`, `pid`, `comment_text`, `comment_date`, `comment_type`
)
(
    SELECT 180, 2, NULL, '2012-07-26 10:19:00', 'tag'
    FROM comment
    WHERE `mid`=180 AND
          `pid`=2 AND
          `comment_type`='tag'
    LIMIT 1
);

EDIT: Better way to do this:

to remove duplicates from a table see here

ALTER IGNORE TABLE comment ADD UNIQUE KEY ix1(mid, pid, comment_type);

INSERT IGNORE INTO comment
(
 `mid`, `pid`, `comment_text`, `comment_date`, `comment_type`
)
VALUES 
(
 SELECT 180, 2, NULL, '2012-07-26 10:19:00', 'tag'
);

add an ignore

INSERT IGNORE INTO comment ...

to prevent duplicate inserts. You can't use a where clause in an insert .

If you use the IGNORE keyword, errors that occur while executing the INSERT statement are treated as warnings instead. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row still is not inserted, but no error is issued.

Taken from the MySQL INSERT Documentation

That means you should add a unique key to your table (if you haven't already) to make the DB check for duplicates by itself. If the DB finds a duplicate no INSERT will be made.

if you want to make an UPDATE in case of duplicates that is possible too. See here

为什么不仅仅创建由mid,pid和comment_type列组成的唯一索引?

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