dragon0023 2015-06-08 07:36
浏览 47
已采纳

数据不一致,使用MySQL,PHP,Yii2

I'm building a system which tracks records of views of an image.

The main tables in this project are the view table and max_view table. The view table keeps the date, time and number of views. And the max_view table keep tracks of the maximum number that an image can be viewed.

Every time when an image is being loaded. I will store the date and time into the view table. And will minus 1 from total max views of the image in max_view table.

Table example:

View Table

id  | image_id |  datetime             |  username
1     1            2015-03-02 02:30:34     user1
2     1            2015-03-02 02:32:34     user2
3     2            2015-03-03 01:40:34     user1

Max_view Table

id   |   max_view   | image_loc
1        1000         /image/image_1.jpg
2        500          /image/image_2.jpg

My SQL query in yii2 framework below:

Choose an image randomly:

$row = Yii::$app->db->createCommand("SELECT id FROM image_source ORDER BY RAND()")->queryOne();

Insert into view table:

Yii::$app->db->createCommand()->insert('view', [
    'image_id' => $row['image_id'],
    'datetime' => $datetime,
    'username' => $user,
])->execute();

Update max view count:

Yii::$app->db->createCommand("UPDATE max_view SET max_view=max_view-1 WHERE id=$image_id")->execute();

My problem is, when there are large number of users view at the same time. The data is not consistence. The data inserted in view table tend to be more sometimes. For example, if there are 10 people viewed the same image. The view table supposedly to have 10 records and max_view table will minus 10 from the total of max view of that image. But somehow, it sometimes only minus 9 from the max_view.

If I test it on my local machine, it works flawlessly. May I know how do I solved this? I'm suspecting that the server is not fast enough to capture the max_view data. How do I make it more consistent ?

  • 写回答

1条回答 默认 最新

  • dp815292 2015-06-08 08:00
    关注

    If you try to edit data from a SQL database at the same time from different hosts, that often does not work properly. Instead of this just add a New entry into a table which just says "1" and the image ID and count the entrys every time until they reach 1000.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我这模型写的不对吗?为什么lingo解出来的下面影子价格这一溜少一个变量
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波