简体   繁体   中英

How to update 3 tables with INNER JOIN?

I have 3 tables that look like this:

  1. users:

    • ID
    • Name (string)
    • ageID (int)
    • descID (int)
  2. users_age:

    • ageID (int)
    • age_group (string)
  3. users_desc:

    • descID (int)
    • desc_text (string)

Now, I have an 'edit' form which uses INNER JOIN to display the corresponding string column in the place of ageID and descID instead of the IDs.

And a button that directs to updateUser.php to update the data. I know I can update name with:

$sql = "UPDATE users SET
        Name = '$uName',
        WHERE ID = '$uID'";

But how can I update the ageID/descID (INTEGER value) column in USERS table with the ID of ageID/descID from the age_group/desc_text equivalent ID when the form page is sending the string columns to the updateUser.php file?

I hope my explanation wasn't very confusing!

If the strings in the tables are unique (and they should be) you can update to the output of a SELECT statement

$sql = "UPDATE users
        SET ageID = (SELECT ageID FROM users_age WHERE age_group = '$uAgeString')
        WHERE ID = '$uID'";

You can do something analogous with the other table.

However - it would be better to get the ID from web page. Typically you do that by setting the value attribute of the option tag:

<select name='uAgeID'>
  <option value='1'>Young</option>
  <option value='2'>Middling</option>
  <option value='3'>Old</option>
</select>

That way you can have a simpler SQL statement:

$sql = "UPDATE users
        SET ageID = $uAgeString
        WHERE ID = '$uID'";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM