gpt4 book ai didi

MySQL 在一个查询中选择所有数据并更新

转载 作者:行者123 更新时间:2023-11-29 11:18:48 26 4
gpt4 key购买 nike

我有 3 张 table 。其中之一存储 users_data。

我运行这个sql代码:

SELECT @rownum := @rownum + 1 AS position,
user_id, score, user_type
FROM users_data
ORDER BY score DESC

结果如下:

enter image description here

我有 2 张 table 供这样的用户使用

我的 table

users1

+----+----------+----------+
| id | username | position |
+----+----------+----------+
| 1 | uname | 0 |
| 2 | uname2 | 0 |
| 3 | uname3 | 0 |
| 5 | uname5 | 0 |
| 11 | uanme11 | 0 |
| 12 | uname12 | 0 |
+----+----------+----------+

users0

+-----+----------+----------+
| id | username | position |
+-----+----------+----------+
| 1 | uname | 0 |
| 111 | uname111 | 0 |
| 138 | uname138 | 0 |
| 241 | uname241 | 0 |
+-----+----------+----------+

我想在一个查询中运行 SELECT sql 时更新用户位置。

if user_type is 0, update users0.position = @rownum
if user_type is 1, update users1.position = @rownum

结果必须是这样的:

users1

+----+----------+----------+
| id | username | position |
+----+----------+----------+
| 1 | uname | 1100 |
| 2 | uname2 | 1100 |
| 3 | uname3 | 1075 |
| 5 | uname5 | 1075 |
| 11 | uanme11 | 1075 |
| 12 | uname12 | 1175 |
+----+----------+----------+

users0

+-----+----------+----------+
| id | username | position |
+-----+----------+----------+
| 1 | uname | 1075 |
| 111 | uname111 | 1025 |
| 138 | uname138 | 1025 |
| 241 | uname241 | 1025 |
+-----+----------+----------+

最佳答案

update users1,users0
set users1.position = (
select v.position
from
(SELECT
@rn1 := @rn1 + 1 AS position,
users_id, score, user_type
FROM (select @rn1:=0) rn, users_data ud
ORDER BY score DESC
) v
where v.users_id = users1.id and v.user_type = 1
)
,
users0.position = (
select s.position
from
(SELECT
@rn := @rn + 1 AS position,
users_id, score, user_type
FROM (select @rn:=0) rn, users_data ud
ORDER BY score DESC
) s
where s.users_id = users0.id and s.user_type = 0
)

where 1 = 1
;

结果

+-----+------+----------+----------+
| src | id | username | position |
+-----+------+----------+----------+
| u1 | 12 | uname12 | 1 |
| u1 | 1 | uname | 2 |
| u1 | 2 | uname2 | 3 |
| u1 | 11 | uanme11 | 4 |
| u1 | 5 | uname5 | 5 |
| u1 | 3 | uname3 | 6 |
| u0 | 1 | uname | 7 |
| u0 | 111 | uname111 | 8 |
| u0 | 138 | uname138 | 9 |
| u0 | 241 | uname241 | 10 |
+-----+------+----------+----------+
10 rows in set (0.00 sec)

关于MySQL 在一个查询中选择所有数据并更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39313127/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com