Chinaunix

标题: 求助,多表关联更新问题 [打印本页]

作者: Linux521    时间: 2016-09-26 09:20
标题: 求助,多表关联更新问题
目前有三个表A(uacct,user_name),B(uid,username),C(uid,realname);

A.user_uacct=B.username

B.uid=C.uid

想取出A.user_name更新到C.realname. 如何写出批量更新的SQL呢,谢谢。

作者: seesea2517    时间: 2016-09-27 11:02
回复 1# Linux521
试一下:
  1. mysql> select * from A;
  2. +-------+-----------+
  3. | uacct | user_name |
  4. +-------+-----------+
  5. | aaa   | axx       |
  6. | bbb   | bxx       |
  7. | ccc   | cxx       |
  8. +-------+-----------+
  9. 3 rows in set

  10. mysql> select * from B;
  11. +-----+-----------+
  12. | uid | user_name |
  13. +-----+-----------+
  14. | 1   | aaa       |
  15. | 2   | bbb       |
  16. | 3   | ccc       |
  17. +-----+-----------+
  18. 3 rows in set

  19. mysql> select * from C
  20. ;
  21. +-----+----------+
  22. | uid | realname |
  23. +-----+----------+
  24. | aaa | NULL     |
  25. | bbb | NULL     |
  26. | ccc | NULL     |
  27. +-----+----------+
  28. 3 rows in set

  29. mysql> update A, B, C set realname = A.user_name where A.uacct = B.user_name and B.uid = C.uid;
  30. Query OK, 3 rows affected
  31. Rows matched: 3  Changed: 3  Warnings: 0
  32. mysql> select * from C;
  33. +-----+----------+
  34. | uid | realname |
  35. +-----+----------+
  36. | 1   | axx      |
  37. | 2   | bxx      |
  38. | 3   | cxx      |
  39. +-----+----------+
  40. 3 rows in set

  41. mysql>
复制代码



作者: will009    时间: 2016-09-27 11:21
回复 2# seesea2517
不对吧,你的例子中B.uid=C.uid吗


作者: seesea2517    时间: 2016-09-27 15:40
回复 3# will009
感谢指出,那是最初的输出,后来测试发现做错测试数据了,改完后直接测试没重新输出截图了,这是改下后的 uid 数据:
  1. ysql> select * from B;
  2. +-----+-----------+
  3. | uid | user_name |
  4. +-----+-----------+
  5. | 1   | aaa       |
  6. | 2   | bbb       |
  7. | 3   | ccc       |
  8. +-----+-----------+
  9. 3 rows in set

  10. mysql> select * from C
  11. ;
  12. +-----+----------+
  13. | uid | realname |
  14. +-----+----------+
  15. | 1   | axx      |
  16. | 2   | bxx      |
  17. | 3   | cxx      |
  18. +-----+----------+
  19. 3 rows in set
复制代码



作者: Linux521    时间: 2016-10-13 17:03
本帖最后由 Linux521 于 2016-10-13 17:06 编辑

感谢 seesea2517 will009   。已解决,当时想多了点




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2