MySQL如何在单个查询中执行if是否存在增量 [英] MySQL how to do an if exist increment in a single query

查看:49
本文介绍了MySQL如何在单个查询中执行if是否存在增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只希望有一个表来按天存储许多事件.

I just wish to have a table to store a number of events by day.

提供表格:

create table totals (
    entryday date,
    total int(11) default 0 not null,
    primary key (entryday) );

如何编写一个递增但创建必需查询的简单查询?

How can I write a simple query which increments, but creates an necessary?

我尝试过-但是它没有增加(它保持为1):

I tried this - but it is not incrementing (it remains at 1):

REPLACE totals SET total = total + 1, entryday = "08-01-11"

显然,这可以很简单地在2个查询中完成,但是它是通过JDBC调用进行的,并且可以被多次调用,因此1个查询会更好.

Obviously this could be done in 2 queries quite simply, but it's through JDBC calls and may be called many times, so 1 query would be better.

推荐答案

您可能想要

You probably want ON DUPLICATE KEY:

INSERT INTO totals (entryday, total)
VALUES ("08-01-11", 1)
ON DUPLICATE KEY UPDATE total = total + 1

如果该日期尚无行,则将"08-01-11" total设置为1,如果total设置为1,则将其递增1.

That'll set the "08-01-11" total to 1 if a row doesn't already exist for that date and increment the total by 1 if it does.

这篇关于MySQL如何在单个查询中执行if是否存在增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆