tags:

views:

55

answers:

3
+2  Q: 

MySQL sub query

UPDATE members 
    SET money=money+100 
WHERE username IN (    
                   SELECT username 
                     FROM forum
                  );

Lets say I wanted to give each of my members 100 money for each post in my forum. This query works but if one member has posted more than once, they only get 100. Could someone correct this query please?

A: 

I think you misunderstand - your query will update all rows in members where the username exists in the forum table, not jsut the first match for each member.

RedFilter
A: 

I think you want this to be a dynamic query instead of updating the member table:

select username, count(username)*100 as money
from forum
group by username
order by username

if you must have it in the member table, then this query can be used in your update similar to the following:

update members m 
set money = (select count(username)*100 from forum f where f,username = m.username )

another issue here is when to do the update - this would best be done in a trigger so it would look more like a parameterized statement for only the current username in the current forum insert.

hth

Randy
That doesn't perform the update as requested. Perhaps you could expand on your answer?
Mark Byers
You have to join this table with members table to update the money field in members
Zai
there is no where clause on the main query, wouldn't this just update every row in the members table?
Juddling
yes - unless you place this code in a trigger, then you would add an additional and condition to apply to only this current row. (although i think this is a mutation condition - so it might be tricky)
Randy
+1  A: 

Do the same as the subquery in the where clause. Instead of money=money+100 put update members m set money=money+100*(select count(f.username) from forum f where f.username = m.username)

ondesertverge