MySQL:根据条件更新表中的列

时间:2017-01-01 16:34:13

标签: mysql sql select sql-update

我有这个查询

    public class Array {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int[] array = {13,25,35,74,5,16,73,8};
        Scanner sc = new Scanner(System.in);

        System.out.println("Please Enter Value to Swipe:");
        int position = sc.nextInt();
        sc.nextLine();
        List<Integer> NewArray = new ArrayList<Integer>();  

        if(position > array.length){
            position = position % array.length;
        }
        for(int i = 0;i <= array.length-1;i++) {
            NewArray.add(array[i]);
        }
        System.out.println("  "+NewArray);

        for(int k = position;k <= position;k++) {

              NewArray.add(0,NewArray.get(NewArray.size()));   
              System.out.println("  "+NewArray);
              NewArray.remove(array.length);

        }
         System.out.println("  "+NewArray);
    }

}

选择我需要的行。

我想设置

SELECT *, min(id) 
FROM mytable 
WHERE col2='specval' 
GROUP BY col3

分别为上面选择的行。

那么,如何通过将该表中的col4分别设置为每个选定行的col4 = col3 + 1000来更新那些行?

谢谢。

3 个答案:

答案 0 :(得分:1)

你可以使用这样的查询:

UPDATE mytable
set col4 = col3+1000
WHERE id in (
  SELECT * FROM (
    SELECT min(id) 
    FROM mytable 
    WHERE col2='specval' 
    GROUP BY col3
  ) as myids
);

答案 1 :(得分:1)

您可以在JOIN中使用UPDATE:

UPDATE mytable t1
        INNER JOIN
    (SELECT 
        col3, MIN(id) id
    FROM
        mytable
    GROUP BY col3) t2 ON t1.col3 = t2.col3 AND t1.id = t2.id 
SET 
    t1.col4 = t1.col3 + 1000;

答案 2 :(得分:0)

您也可以在update子句中使用WHERE。所以取决于&#34;选择&#34;意味着你(我猜你的SELECT),你可能会这样做:

UPDATE mytable
SET col4 = col3+1000
WHERE col2 = 'specval';