我想插入一行,如果该行不存在且存在,我想更新该行。我目前正在使用mysql 5.1.67
这是我的MYSQL代码:
IF EXISTS(select * from tabSingles where `doctype` = 'Control Panel' and `field` = 'time_zone')
THEN
update tabSingles SET `value` = 'Asia/Calcutta' where `doctype` = 'Control Panel' and `field` = 'time_zone'
ELSE
insert into tabSingles (`doctype`,`field`,`value`) VALUES ('Control Panel','time_zone','Asia/Calcutta')
但这总是会引发错误:
ERROR 1064 (42000): 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 'IF EXISTS(select * from tabSingles where `doctype` = 'Control Panel' AND `fi' at line 1
我知道我可以使用" REPLACE"或" INSERT .... ON DUPLICATE KEY"执行此操作但问题是此表中没有PRIMARY KEY或UNIQUE KEY,并且我正在处理的项目是OPEN-SOURCE,因此我们无法更改DATABASE SCHEMA。如果我们这样做,那么每次我们从他们那里得到新的更新时我们都必须继续这个过程。
所以任何人都可以帮助我。
由于
答案 0 :(得分:0)
试试这个。
IF EXISTS(SELECT * FROM tabSingles WHERE `doctype` LIKE 'Control Panel' AND `field` LIKE 'time_zone');
BEGIN
UPDATE tabSingles SET `value` = 'Asia/Calcutta' WHERE `doctype` LIKE 'Control Panel' AND `field` LIKE 'time_zone'
END;
ELSE
BEGIN
INSERT INTO tabSingles (`doctype`,`field`,`value`) VALUES ('Control Panel','time_zone','Asia/Calcutta')
END IF;
OR
IF NOT EXISTS(SELECT * FROM [tabSingles] WHERE `doctype` LIKE 'Control Panel' AND `field` LIKE 'time_zone');
BEGIN
INSERT INTO [tabSingles] (`doctype`,`field`,`value`) VALUES ('Control Panel','time_zone','Asia/Calcutta');
END;
ELSE
BEGIN
UPDATE [tabSingles] SET `value` = 'Asia/Calcutta' WHERE `doctype` LIKE 'Control Panel' AND `field` LIKE 'time_zone'
END IF;
或者,手动试用
$result = mysql_query("SELECT * FROM tabSingles WHERE `doctype` LIKE 'Control Panel' AND `field` LIKE 'time_zone';");
IF (mysql_affected_rows()==0)
{
$result = mysql_query("INSERT INTO tabSingles (`doctype`,`field`,`value`) VALUES ('Control Panel','time_zone','Asia/Calcutta');");
}
ELSE
{
$result = mysql_query("UPDATE tabSingles SET `value` = 'Asia/Calcutta' WHERE `doctype` LIKE 'Control Panel' AND `field` LIKE 'time_zone';");
}
答案 1 :(得分:0)
Replace
首先删除行(通过唯一索引),然后插入一个新行。如果您愿意,可以手动执行此操作,而不是通过唯一索引。如果没有要删除的行,那就没问题了。这和replace
一样贵,只要确保你有一个适当的删除索引,你就可以了。
DELETE FROM tabsingles
WHERE ` doctype ` = 'Control Panel'
AND ` field ` = 'time_zone';
INSERT INTO tabsingles
( ` doctype ` ,
` field ` ,
` value ` )
VALUES ('Control Panel',
'time_zone',
'Asia/Calcutta');