mysql 基于同一表中的不同行更新行

cxfofazt  于 2024-01-05  发布在  Mysql
关注(0)|答案(1)|浏览(132)

我使用此表存储一些键,并且我想更新列“value”,其中列“name”仅在用户的国家/地区为CA时才等于name_1
| 用户|名称|值|
| --|--|--|
| 1 |名称_1| 0 |
| 1 |国家|FR|
| 2 |名称_1| 0 |
| 2 |国家|CA|
| 3 |名称_1| 0 |
| 3 |国家|CA|
预期产出:
| 用户|名称|值|
| --|--|--|
| 1 |名称_1| 0 |
| 1 |国家|FR|
| 2 |名称_1|第一章|
| 2 |国家|CA|
| 3 |名称_1|第一章|
| 3 |国家|CA|
我想我可以使用存储过程来完成这个任务,但我不知道是否有更简单的方法来使用单个查询。谢谢
这是我创建的存储过程,它可以工作,但我真的很想执行一些更简单的东西。

  1. DELIMITER //
  2. CREATE PROCEDURE updateName1()
  3. BEGIN
  4. DECLARE done BOOLEAN DEFAULT FALSE;
  5. DECLARE userId INT;
  6. -- Declare a cursor for the SELECT query
  7. DECLARE cur CURSOR FOR
  8. SELECT distinct user FROM my_table WHERE name = 'country' AND value = 'CA';
  9. -- Declare handler for when no more rows found
  10. DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
  11. -- Open the cursor
  12. OPEN cur;
  13. -- Loop through the result set
  14. read_loop: LOOP
  15. FETCH cur INTO userId;
  16. -- Exit loop when no more rows
  17. IF done THEN
  18. LEAVE read_loop;
  19. END IF;
  20. -- Perform actions with each row here
  21. -- For example, print the values
  22. UPDATE my_table SET value = 1 WHERE name = 'name_1' AND user = userId;
  23. END LOOP;
  24. -- Close the cursor
  25. CLOSE cur;
  26. END //
  27. DELIMITER ;

字符串

o75abkj4

o75abkj41#

应该是这样的:

  1. Update your_table t1 join your_table t2 on t1.user = t2.user
  2. Set value = 1
  3. Where t1.name = 'name_1' and
  4. t2.name = 'country' and
  5. t2.value = 'CA'

字符串

相关问题