仅按列值更新同一组的行

时间:2017-05-12 08:38:14

标签: mysql

给定一个包含3列及其中几行的表:

+--------+------------+--------+
|  name  | postalcode | toggle |
+--------+------------+--------+
| john   |      10100 |      0 |
| joe    |      10100 |      0 |
| tom    |      10100 |      0 |
| steven |      77777 |      0 |
| jerry  |      10100 |      0 |
| albert |      77777 |      0 |
| paul   |      77777 |      0 |
| mary   |      88888 |      0 |
| louis  |      10100 |      0 |
| claire |      77777 |      0 |
+--------+------------+--------+

我希望UPDATE toggle的值为LIMITNpostalcode,但toggle行的[mary]行不能包含[steven, albert, paul, claire][john, joe, tom, jerry, louis]列。

例如:

  • 如果我想更新2行,则只会更新[steven, albert, paul, mary, claire]
  • 如果我想UPDTE 4行, //folderBrowserDialog1.ShowDialog(); //string xx = folderBrowserDialog1.SelectedPath; //string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath); //folderBrowserDialog1.ShowDialog(); //string yy = folderBrowserDialog1.SelectedPath; //foreach (string file in files) //{ // File.Copy(xx + "\\" + Path.GetFileName(file), yy + "\\" + Path.GetFileName(file)); 会更新。
  • 如果我想更新5行,=$query3 = "SELECT * FROM students where `id` = '$edit_data'"; 会更新。

考虑到我将处理N行,如何以方便/高效的方式执行此操作?

1 个答案:

答案 0 :(得分:0)

考虑到真实数据集更复杂,我需要保证选择要更新的组的随机性,我可能最终会做这样的事情;所以为了分享:

set @N:=2;
set @i:=0;
select postalcode,sum(NBR)
from (
    SELECT postalcode
            , if(@i+NBR>@N,0,1) as elected 
            , if(@i+NBR>@N,@i,@i:=@i+NBR) as indice
            , NBR
    FROM (  SELECT postalcode,COUNT(DISTINCT name) AS NBR FROM myTable GROUP BY postalcode ORDER BY RAND() ) A
    GROUP BY postalcode
    having elected= 1
    ORDER BY postalcode
) a GROUP BY postalcode
;