Here is a better way to accomplish an INSERT and UPDATE without affecting the auto increment and on top of that getting back the primary key in either scenario in a consistent way. It does involve multiple commands but can be done on one line if desired. This would be in a case where one or more fields make up a unique constraint like in this case country.
If you want the primary key back from INSERT or UPDATE only null values
SET @now=NOW();
SET @country='Example Country',@country_code='EC',@country_overview='An example country overview.';
INSERT INTO country (country, country_code, country_overview, added_at, updated_at)
SELECT @country,@country_code,@country_overview, @now, @now
FROM dual
WHERE NOT EXISTS (
SELECT 1 FROM country WHERE country=@country
);
SELECT countryid INTO @countryid FROM country WHERE country=@country;
UPDATE country
SET
country_code = @country_code,
country_overview = @country_overview,
updated_at = @now
WHERE countryid = @countryid AND added_at <> @now;
If you want the primary key back from INSERT or UPDATE only null values
SET @now=NOW();
SET @country='Example Country',@country_code='EC',@country_overview='An example country overview.';
INSERT INTO country (country, country_code, country_overview, added_at, updated_at)
SELECT @country,@country_code, @now, @now
FROM dual
WHERE NOT EXISTS (
SELECT 1 FROM country WHERE country=@country
);
SELECT countryid INTO @countryid FROM country WHERE country=@country;
UPDATE country
SET
country_code = COALESCE(country_code, @country_code),
country_overview = COALESCE(country_overview, @country_overview),
updated_at = @now
WHERE countryid = @countryid AND added_at <> @now;
There are few other ways you can work with this to get the primary key back you could do the following as your last statement.
SELECT @countryid;