For Programmers: Free Programming Magazines  


Home > Archive > PHP SQL > June 2006 > is it possible in MySQL?









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author is it possible in MySQL?
Gerwazy

2006-06-24, 8:06 am

One of field of my database is amount.
How can I update (set mark="X") as many rows as sum of the amount give
me <=20? (in Id order DESC)


|id| amount |
|1 | 8 | update this
|2 | 7 | this
|3 | 3 | and this
|4 | 11 | but not this (>20!)
Andy Hassall

2006-06-24, 8:06 am

On Fri, 23 Jun 2006 00:39:03 +0200, Gerwazy <gerwazy@nomail.no> wrote:

>One of field of my database is amount.
>How can I update (set mark="X") as many rows as sum of the amount give
>me <=20? (in Id order DESC)
>
>|id| amount |
>|1 | 8 | update this
>|2 | 7 | this
>|3 | 3 | and this
>|4 | 11 | but not this (>20!)


MySQL won't let you update a table referenced in a subquery, at least not in
the version I'm on (4.1), so have to go via temporary table. Maybe 5.0 allows
this directly.

mysql> create temporary table tx as
-> select t1.id
-> from t t1
-> join t t2 where (t2.id <= t1.id)
-> group by t1.id
-> having sum(t2.amount) <= 20;
Query OK, 3 rows affected (0.01 sec)
Records: 3 Duplicates: 0 Warnings: 0

mysql> update t
-> set t.mark = 'x'
-> where t.id in (select id from tx);
Query OK, 3 rows affected (0.00 sec)
Rows matched: 3 Changed: 3 Warnings: 0

mysql> drop table tx;
Query OK, 0 rows affected (0.00 sec)

mysql> select * from t;
+------+--------+------+
| id | amount | mark |
+------+--------+------+
| 1 | 8 | x |
| 2 | 7 | x |
| 3 | 3 | x |
| 4 | 11 | NULL |
+------+--------+------+
4 rows in set (0.00 sec)

--
Andy Hassall :: andy@andyh.co.uk :: http://www.andyh.co.uk
http://www.andyhsoftware.co.uk/space :: disk and FTP usage analysis tool
Gerwazy

2006-06-24, 8:06 am

Andy Hassall napisaƂ(a):

> MySQL won't let you update a table referenced in a subquery, at least not in
> the version I'm on (4.1), so have to go via temporary table. Maybe 5.0 allows
> this directly.
>
> mysql> create temporary table tx as


than You - it works fine!
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com