如果我提供的名称值不存在,我想在我的客户表中的行中插入值, 经过一些搜索,我使用这个SQL查询来做它并且它不起作用:(
IF NOT EXISTS (SELECT Name FROM customer WHERE Name = 'Riyafa')
INSERT INTO customer (`Name`, `Address`, `ContactNo`,`Total_amout`)
VALUES ('Riyafa', 'ABC', '555','1000');
请告诉我为什么这不正确。
答案 0 :(得分:1)
if
语句仅在存储过程,函数和触发器中允许。一种方法是:
INSERT INTO customer (`Name`, `Address`, `ContactNo`,`Total_amout`)
SELECT name, address, contactno, total_amount
FROM (SELECT 'Riyafa' as name, 'ABC' as address, '555' as contact no, '1000' as total_amount) t
WHERE NOT EXISTS (SELECT 1 FROM customer c WHERE c.name = t.name);
然而,更好的方法是让数据库对名称强制执行唯一性。首先创建一个唯一的索引或名称:
CREATE UNIQUE INDEX idx_customer_name ON customer(name);
然后使用on duplicate key update
:
INSERT INTO customer (`Name`, `Address`, `ContactNo`,`Total_amout`)
SELECT 'Riyafa' as name, 'ABC' as address, '555' as contact no, '1000' as total_amount
ON DUPLICATE KEY UPDATE Name = VALUES(Name);
表达式ON DUPLICATE KEY UPDATE Name = VALUES(Name)
实际上没有做任何事情,但它会阻止INSERT
返回错误。