我试图在插入之前确保一行不存在但是出现语法错误,这是我的sql:
IF NOT EXISTS
( SELECT *
FROM profile_views
WHERE (profile_view_user = ?
AND profile_view_viewing = ?)
)
BEGIN
INSERT INTO profile_views
(
profile_view_user,
profile_view_viewing,
profile_view_ip
)
VALUES
(
?,
?,
?
)
END;
CREATE TABLE IF NOT EXISTS `profile_views` (
`profile_view_id` int(11) NOT NULL,
`profile_view_user` int(11) NOT NULL,
`profile_view_viewing` int(11) NOT NULL,
`profile_view_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`profile_view_ip` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
我得到的错误是:
警告:PDOStatement :: execute():SQLSTATE [42000]:语法错误或 访问冲突:1064您的SQL语法有错误;检查 手册,对应右边的MySQL服务器版本 在'IF NOT EXISTS附近使用的语法(SELECT * FROM profile_views WHERE (亲'在第1行
如何修复我的SQL查询?
答案 0 :(得分:0)
尝试使用:
INSERT INTO profile_views(profile_view_user, profile_view_viewing, profile_view_ip)
SELECT * FROM (SELECT ?, ?, ?) AS tmp
WHERE NOT EXISTS (
SELECT * FROM profile_views WHERE
(profile_view_user = ? AND profile_view_viewing = ?') LIMIT 1;