我现在正在尝试创建一个查询,检查表中是否存在记录,然后不执行任何其他操作。我已经看到了此任务的多个示例。从这些示例中,我创建了一个查询。
查询:
CREATE PROCEDURE Answer ()
IF EXISTS
(SELECT * FROM answer WHERE a = 'a' && b = 'b' && e = 'e ' && timestamp = '1423828119' )
THEN
BEGIN
SELECT 'This record already exists!'
END
IF ELSE
BEGIN
SELECT 'Record Added'
INSERT INTO answer(a, b, c, d, e, timestamp)
VALUES ('a','b','c','d','e','1423828119')
END
错误:
syntax to use near ' 'IF ELSE BEGIN SELECT 'Record Added' INSERT INTO answer(a, b,'
不是我在mysql中的条件有错误。 请引导我走向正确的方向。
答案 0 :(得分:1)
使用EXISTS
检查查询是否返回任何内容:
if exists(
select *
from answer
where a = 'a' and b = 'b' and e = 'e' and timestamp = '1423828119'
) then begin
select 'This record already exists!'
end else begin
select 'Record Added'
insert into answer(a, b, c, d, e, $timestamp)
values ('a','b','c','d','e ','1423828119')
end
答案 1 :(得分:0)
而不是WHERE a = 'a' && b = 'b' && e = 'e' && timestamp = '1423828119'
您应该使用WHERE a = 'a' AND b = 'b' AND e = 'e' AND timestamp = '1423828119'
(请参阅&&我使用的AND)
您也可以使用IF EXIST
而非if TRUE
之类的内容:
IF EXISTS (select ...) THEN
select ...;
ELSE
...
END IF;
答案 2 :(得分:0)
在大多数DBMS中都有MERGE
语句,但MySQL不支持它。
以下查询不需要存储过程:
INSERT INTO answer(a, b, c, d, e, timestamp)
SELECT 'a','b','c','d','e','1423828119'
WHERE NOT EXISTS
(
SELECT * FROM answer
WHERE a = 'a' AND b = 'b' AND e = 'e' AND timestamp = '1423828119
);