假设下表:
+----+-----------+
| id | session |
+----+-----------+
| 1 | abcd1234 |
| 2 | abcd1234 |
| 3 | abcd1234 |
| 4 | qwert5678 |
| 5 | qwert5678 |
| 6 | abcd1234 |
| 7 | abcd1234 |
| 8 | qwert5678 |
| 9 | abcd1234 |
| 10 | qwert5678 |
| 11 | qwert5678 |
| 12 | qwert5678 |
+----+-----------+
假设我们想要获取给定会话的第一个id,然后将该会话的每个实例设置为所有会话的 ,以使该表变为:
+----+-----------+
| id | session |
+----+-----------+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 4 |
| 5 | 4 |
| 6 | 1 |
| 7 | 1 |
| 8 | 4 |
| 9 | 1 |
| 10 | 4 |
| 11 | 4 |
| 12 | 4 |
+----+-----------+
我们有一个包含大约45M记录的表,并且当按b列分组时,实际上将列b的每个实例更改为min(列a)的值。
有没有办法在单个查询中执行此操作?我们尝试了几个。
update example e
set session =
(select id from
(select id,min(session)
from example as first_id
group by session
) as this_id
);
...哪个错误输出:“子查询返回超过1行”。
update example e
join
(select id
from
(select id,min(session)
from example as first_id
group by session
) as this_id
) as etable
set session = first_id;
...哪个错误输出:“字段列表'中的未知列'first_id'”。也使用'this_id'来达到同样的效果。
和其他查询。这可能在一个查询中吗?我们是不是想错了?
答案 0 :(得分:2)
查询:
<强> SQLFIDDLEExample 强>
UPDATE example
SET session =(SELECT MIN(e2.ID)
FROM (SELECT *
FROM example) e2
WHERE e2.session = example.session)
结果:
| ID | SESSION |
----------------
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 4 |
| 5 | 4 |
| 6 | 1 |
| 7 | 1 |
| 8 | 4 |
| 9 | 1 |
| 10 | 4 |
| 11 | 4 |
| 12 | 4 |