根据日期和用户id检查记录是否存在,如果不创建,则更新记录,同时添加值而不是替换值


Check if a record exists based on date and user id, if not create it, if so update it -while adding values instead of replacing them

我正在尝试使用sql脚本(MySql)创建一个php页面,该脚本将检查用户是否已经添加了当天的记录。如果他们没有,我想创建记录。如果他们有,我想用新信息更新记录。

例如:

1) no record found... add the following info
    user_id     number
    --------    ------
    00001       1
2) database now looks like this
index       date                user_id     number
-----       -----               --------    -------
1       2015-03-23 11:41:51     00001       1

3. php page is called again by the same user the same day month and year just a few minutes later with the following data:
    user_id     number
    --------    ------
    00001       5
4) database should now looks like this
index       date                user_id     number
-----       -----               --------    -------
1       2015-03-23 11:41:51     00001       6 <---notice the numbers are added

5) if the user calls the php page the following day I want it to create a new record.      

我不确定这是否只能用sql完成,或者是否还有php代码需要添加,如果有任何帮助,我们将不胜感激。

------------------编辑-------------------------

我用来添加新记录的代码。

$query = mysqli_query($connection, "INSERT INTO myTable(user_id, number)  
VALUES(00001,1)");

我不知道如何检查带有日期/时间/年份和user_id的记录,也不知道如何像上面的例子中那样添加numbers

您可以执行以下3个步骤:

  1. 在表中创建一个名为day的列,该列只包含日期(不包含时间)。

  2. dayuser_id上创建类型为unique的索引。

  3. 如果该用户和当天的条目已经存在,请在插入中使用on duplicate key语句来触发更新:

    INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c=c+1;

取自:http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html