SELECT from multiple tables

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • TheServant
    Recognized Expert Top Contributor
    • Feb 2008
    • 1168

    #1

    SELECT from multiple tables

    Hi,
    I have been trying to figure this one out for ages and haven't been able to find out if it's even possible, let alone how to do it.
    I have a table of users where some users have a "commander" who will benefit from that users stats. This is updated daily where a users benefits are calculated and updated via a cronjob. I would like to update users, and if they have commanders, update them as well in the same MySQL statement. So the only way I can do it no is like this:
    Code:
    $users = mysql_query( "SELECT id, commander_id FROM users" );
    while( $user = mysql_fetch_array($users) ) {
    mysql_query( "UPDATE users SET money=(money+$production)" WHERE id=$user['id'] );
    if( $user['commander_id'] != 0 ) {
    mysql_query( "UPDATE users SET money=(money+$production/2)" WHERE id=$user['commander_id'] );
    }
    Or something to that effect. This means that for every user found there is atleast one (possibly two) queries. Obviously I cannot have this so I was wondering if anyone has an idea of how to use a JOIN to achieve the same result?

    **EDIT I changed the question so the title does not fit this one... sorry for the confusion.
  • mwasif
    Recognized Expert Contributor
    • Jul 2006
    • 802

    #2
    Is $production will be same for all users?

    Comment

    • TheServant
      Recognized Expert Top Contributor
      • Feb 2008
      • 1168

      #3
      Ahh, sorry, I mistyped. That should include the definition of $production. So the production value to update the user and the commander will come from the user's production value. Should be:
      Code:
      $users = mysql_query( "SELECT id, commander_id, production FROM users" ); 
      while( $user = mysql_fetch_array($users) ) {
      $production = $user['production'];
      mysql_query( "UPDATE users SET money=(money+$production)" WHERE id=$user['id'] );
      if( $user['commander_id'] != 0 ) { 
      mysql_query( "UPDATE users SET money=(money+$production/2)" WHERE id=$user['commander_id'] ); 
      }

      Comment

      Working...