I run into a problem for which I didn't find an answer anywhere: If I have a table in which one specific value(here amount) from multiple records can add into a target record(from the same table), can I do it in a single query? This query below works, just that it only works for the first match(?!).
UPDATE test AS t1
LEFT JOIN test AS t2 ON t1.target = t2.obj_id
SET t2.amount = t2.amount + t1.amount, t1.amount = 0
WHERE t1.amount > 0 AND strcmp(t1.target, "null") <> 0;
-
1Please add some sample data and the expected result after the update.Leigh Riffel– Leigh Riffel2011年01月14日 19:34:00 +00:00Commented Jan 14, 2011 at 19:34
1 Answer 1
I might be missing something here, but maybe it only works for the first match because it sets t1.amount = 0
, which means that record is excluded from a repeated invocation of the same command (whose WHERE
clause requires t1.amount > 0
)?
-
If I have 2 records that have the same target, when I reset the value of one of these(t1.amount = 0), it should not influence the second record, so when the second gets added to the target record, the target should have the sum of the two records. I just get the first record's value in the target, the rest are set to 0.user412– user4122011年01月13日 18:48:22 +00:00Commented Jan 13, 2011 at 18:48