2017-01-16 96 views
0

我有一個簡單的表是這樣的:mysql的更新與選擇最小/最大計數組

id grouped type_error 
-- ------- ------------------ 
1 1-0  TL   
2 1-0  TL   
3 1-0  TL   
4 1-1  TL   
5 1-2  TL  
6 1-2  TL  
7 1-3  TL  
8 1-3  TL  
9 1-3  TL  
10 1-3  TL  

我只是想更新表是這樣的:

id grouped type_error 
-- ------- ------------------ 
1 1-0  FN   
2 1-0  FN   
3 1-0  FN   
4 1-1  TL   
5 1-2  TL  
6 1-2  TL  
7 1-3  FN  
8 1-3  FN  
9 1-3  FN  
10 1-3  FN  

我想更新其中,分組計數爲3分鐘,最大5:

我只是有我這樣的查詢:

update errorlog set type_error = 'FN' where id in 
(select group_concat(id) as ids from errorlog where ids > 2 group by grouped) 

但是,它不工作。我得到的錯誤

未知列 'IDS' 中的 'where子句'

+0

不明白你的榜樣結果。 '分組計數是最小3和最大5',但在ids 1到3的行中,gruoped字段是1-0 – Alfabravo

+0

如果您對計數感興趣,爲什麼包含group_concat – Strawberry

+0

您可以發佈mysql錯誤嗎? –

回答

0

您可以採用如下方案,與子選擇:

UPDATE errorlog SET type_error = 'FN' 
WHERE grouped IN (
    SELECT * FROM (
    SELECT grouped 
    FROM errorlog 
    GROUP BY grouped 
    HAVING COUNT(id) BETWEEN 3 AND 5 
)x 
); 

這裏你可以找到一個工作演示:http://sqlfiddle.com/#!9/311a01/1/0

+0

我不喜歡使用更多的子查詢選擇。 'UPDATE SET錯誤日誌= type_error 'FN' 其中分組(SELECT * FROM(SELECT AS克 分組FROM錯誤日誌ER GROUP BY er.grouped HAVING COUNT(er.id)在3和5)爲E )用@Sebastian' – mosleim

0
UPDATE table SET type_error = 'FN' 
WHERE grouped IN (
    SELECT grouped 
    FROM table 
    GROUP BY grouped 
    HAVING COUNT(id) BETWEEN 3 AND 5 
) 

不幸的是產生在MySQL的錯誤:

ERROR 1093 (HY000): You can't specify target table 'errorlog' for update in FROM clause 

因此擴大在Sebastian答案我會做這兩個步驟:

MariaDB [test]> 
MariaDB [test]> drop table IF EXISTS targets; 
Query OK, 0 rows affected, 1 warning (0.00 sec) 

MariaDB [test]> 
MariaDB [test]> create temporary table IF NOT EXISTS targets as 
    -> (SELECT grouped 
    ->  FROM errorlog 
    ->  GROUP BY grouped 
    ->  HAVING COUNT(id) BETWEEN 3 AND 5); 
Query OK, 2 rows affected (0.01 sec) 
Records: 2 Duplicates: 0 Warnings: 0 

MariaDB [test]> 
MariaDB [test]> UPDATE errorlog a SET type_error = 'FN' 
    -> WHERE exists (select 1 from targets t where t.grouped = a.grouped); 
Query OK, 7 rows affected (0.00 sec) 
Rows matched: 7 Changed: 7 Warnings: 0 

MariaDB [test]> 
MariaDB [test]> select * from errorlog order by id; 
+------+---------+------------+ 
| id | grouped | type_error | 
+------+---------+------------+ 
| 1 | 1-0  | FN   | 
| 2 | 1-0  | FN   | 
| 3 | 1-0  | FN   | 
| 4 | 1-1  | TL   | 
| 5 | 1-2  | TL   | 
| 6 | 1-2  | TL   | 
| 7 | 1-3  | FN   | 
| 8 | 1-3  | FN   | 
| 9 | 1-3  | FN   | 
| 10 | 1-3  | FN   | 
+------+---------+------------+ 
10 rows in set (0.00 sec) 
+1

解釋,我使用更多選擇來忽略錯誤。它看起來就像這樣:'UPDATE錯誤日誌SET type_error = 'FN' 凡在分組(SELECT * FROM(SELECT 爲G 分組從錯誤日誌呃 GROUP BY er.grouped HAVING COUNT(er.id)3至5 )AS e )' – mosleim

+0

不錯。完美的作品。 –