2

假设下表:

+----+-----------+
| 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 ,这样表就变为:

+----+-----------+
| 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' 达到同样的效果。

和其他查询。这可能在单个查询中吗?我们是不是在错误地思考这个问题?

4

1 回答 1

2

询问:

SQLFIDDLE示例

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 |
于 2013-02-28T20:39:55.987 回答