简体   繁体   English

如何使用INNER JOIN更新3个表?

[英]How to update 3 tables with INNER JOIN?

I have 3 tables that look like this: 我有3张桌子,看起来像这样:

  1. users: 用户:

    • ID ID
    • Name (string) 名称(字符串)
    • ageID (int) ageID(int)
    • descID (int) descID(int)
  2. users_age: users_age:

    • ageID (int) ageID(int)
    • age_group (string) age_group(字符串)
  3. users_desc: users_desc:

    • descID (int) descID(int)
    • desc_text (string) desc_text(字符串)

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. 现在,我有一个“编辑”表单,该表单使用INNER JOIN在ageID和descID而不是ID的位置显示相应的字符串列。

And a button that directs to updateUser.php to update the data. 还有一个直接指向updateUser.php来更新数据的按钮。 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? 但是,当表单页面将字符串列发送到updateUser.php文件时,如何使用age_group / desc_text等效ID中的ageID / descID的ID更新USERS表中的ageID / descID(INTEGER值)列?

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 如果表中的字符串是唯一的(应该是唯一的),则可以更新到SELECT语句的输出

$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. 但是-最好从网页获取ID。 Typically you do that by setting the value attribute of the option tag: 通常,您可以通过设置选项标签的value属性来做到这一点:

<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语句:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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