Reputation: 6393
table Lets call it test
----------------------------
| id | catid | value |
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 1 |
| 4 | 1 | 3 |
| 5 | 1 | 4 |
| 6 | 1 | 5 |
| 7 | 2 | 2 |
----------------------------
Suppose i deleted the 2nd row from table. Now the table will become:
----------------------------
| id | catid | value |
| 1 | 1 | 1 |
| 3 | 2 | 1 |
| 4 | 1 | 3 |
| 5 | 1 | 4 |
| 6 | 1 | 5 |
| 7 | 2 | 2 |
----------------------------
So in catid1
, there is no value 2. so the values will become, 1,3,4,5,.... so far so on....
Goal I need to update the values as subtracting 1 from their previous value so that the continuity is maintined (all values goes one up if the condition is met i.e. if bgger than the deleted value).
CODE After delete, i am trying to perform an update query.
UPDATE `test`
SET `value` =
(
SELECT t.param FROM (
SELECT `value`-1 AS param
FROM `test`
WHERE
`catid` = 1 AND `value` > 2
) AS t
)
WHERE
`catid` = 1
AND `value` > 2
Now, the most inner query will return all the rows which has value >2 where as the update expects a scalar value of string or numeric.
So the question is how can i return the value in the innermost query with respect to what row is update query targeting?
e.g. If update query is trying to update the row with id 4, the innermost query will retreive the value
column with the same row id only and give it back to outer query (after subtracting 1).
Is there any alternative approach in this?
Upvotes: 0
Views: 1238
Reputation: 79979
JOIN
that table with this subquery like this:
UPDATE test t1
INNER JOIN
(
SELECT
id, catid, value - 1 AS value
FROM test
WHERE catid = 1
AND value > 2
) AS t2 ON t1.id = t2.id
SET t1.value = t2.value;
But there is no need for this subquery, you can do this directly like this:
UPDATE test t1
SET value = value - 1
WHERE catid = 1
AND value > 2;
However, You might need to fix that column id
to match those values like this:
UPDATE test AS t1
INNER JOIN
(
SELECT
*,
(@rownum := @rownum + 1) AS newID
FROM test, (SELECT @rownum := 0) AS t
ORDER BY Id
) AS t2 ON t1.id = t2.id
SET t1.id = t2.newId,
t1.value = CASE
WHEN t1.catid = 1 AND t1.value > 2 THEN t2.value - 1
ELSE t1.value
END;
Upvotes: 1