What I want to do is something that has the following logic:
IF EXISTS (SELECT * FROM people WHERE ID = 168)
THEN UPDATE people SET calculated_value = complex_queries_and_calculations
WHERE ID = 168
.., so to update a field of a given record if that record contains a given data, and else do nothing. To generate the data which would be used for the update, I need to query other tables for values and make some calculations. I want to avoid these queries + calculations, if there's actually nothing to update. And in this case, simply do nothing. Hence, I guess that putting for example an EXIST clause inside a WHERE clause of the UPDATE statement would end in many queries and calculations made in vain.
How can I only UPDATE conditionally and else do nothing, and make sure that all the queries + calculations needed to calculate the value used for the update are only made if the update is needed? And then, in the end, only do the update if complex_queries_and_calculations
is not NULL?
My best solution so far uses a Common Table Expression (WITH
clause), which makes it impossible to short-circuit. Anyway, such that you can understand the logic I'm trying to achieve, I'm showing what I've been trying so far (without success; code below is not working and I don't know why..):
-- complex queries and calculations; return result as t.result
WITH t AS(complex queries and calculations)
UPDATE target_table
SET
CASE
WHEN t.result IS NOT NULL
THEN target_table.target_column = t.result WHERE target_table.PK = 180
END;
UPDATES (Still saying syntax error, still not working)
WITH t AS(complex_queries_and_calculations AS stamp)
UPDATE target_table
SET target_column =
CASE
WHEN t.stamp IS NULL
THEN target_column
ELSE t.stamp
END
WHERE ID = 168;
Not even this is working (still reporting syntax error on UPDATE line):
WITH t AS(complex_queries_and_calculations AS stamp)
UPDATE target_table
SET target_column = target_column
WHERE ID = 168;
(eventual better approaches which avoid redundant target_column = target_column updates welcome)
With select it works, so I'm totally not understanding the syntax error #1064 it returns for my update query:
WITH t AS(complex_queries_and_calculations AS stamp)
SELECT
CASE
WHEN t.stamp IS NULL
THEN "Error!"
ELSE t.stamp
END
FROM t;
ADDITIONAL INFO
It seems like MariaDB actually does not support CTE
s with UPDATE
statements; correct me if I'm wrong... So I tried the following:
UPDATE people AS p
INNER JOIN (queries_and_calculations AS result) t
ON p.ID <> t.result -- just to join
SET p.target_column = t.result
WHERE p.ID = 168
AND t.result IS NOT NULL;
and now it's saying:
#4078 - Illegal parameter data types varchar and row for operation '='