具有最小ID日期的SQL更新行

时间:2015-06-11 09:10:27

标签: mysql min

我有一个带有id,date,x的表

id         date         x
1  2015-06-09 12:20:45  1
1  2015-06-10 10:21:55  1
2  2015-06-08 12:34:12  1
2  2015-06-11 13:11:13  1
3  2015-06-07 14:50:44  1
3  2015-06-01 11:12:14  1

现在我想用每个id的最早日期增加x行。所以我希望这个出来:

id         date         x
1  2015-06-09 12:20:45  2
1  2015-06-10 10:21:55  1
2  2015-06-08 12:34:12  2
2  2015-06-11 13:11:13  1
3  2015-06-07 14:50:44  1
3  2015-06-01 11:12:14  2

我的尝试方式:

UPDATE Table
SET x=x+1
where date=
(SELECT MIN(date)
FROM Table
WHERE id=??)

??是我不知道该怎么做的地方。此外,我收到错误,因为我无法在FROM子句"中指定更新目标表。也许这是一种完全错误的方式,我希望有人可以帮助我

3 个答案:

答案 0 :(得分:0)

试试这个:

UPDATE Table
SET x=x+1
where date in
(SELECT MIN(date)
FROM Table
group by id)

答案 1 :(得分:0)

按ID分组获取最小日期..

<program-name index="1" app-name="some app name" percent="some percent"></program-name>
<program-name index="2" app-name="some app name" percent="some percent"></program-name>

.directive('programName', function () {
    return {
        restrict: 'AE',
        replace: true,
        template: '<span><temp1 ng-show="checkNumber(1)"></temp1><temp2 ng-show="checkNumber(2)"></temp2></span>',
        scope: {
            appName: '=',
            index: '@',
            percent: '='
        },
        link: function (scope, element, attr) {
            scope.checkNumber = function (number) {
                return number && scope.index && parseInt(number) == parseInt(scope.index);
            };
        }
    }
})

.directive('temp1', function () {
    return {
        restrict: 'AE',
        replace: true,
        template: '<h2 class="que t1">{{appName.name}} {{appName.company}}{{percent}}</h2>',
        scope: {
            appName: '=',
            percent: '='
        },
        link: function (scope, element, attr) {
        }
    }
})

.directive('temp2', function () {
    return {
        restrict: 'AE',
        replace: true,
        templateUrl: 'htmlTemp/activeHTML.html',
        scope: {  // not sure what you need here
            appName: '=',
            percent: '='
        },
        link: function (scope, element, attr) {
        }
    }
})

答案 2 :(得分:0)

您可以使用JOIN进行更新并更新为

update table_name t1
join(
  select id,min(date) as date from table_name
  group by id
)t2 on t1.id = t2.id and t1.date = t2.date
set t1.x = t1.x+1 ;

http://www.sqlfiddle.com/#!9/fec17/1