drti52047 2014-12-11 21:28
浏览 32

MySQL - 选择行时更新表

I have the following query:

SELECT name FROM restaurants WHERE city='Kalmar' LIMIT 100

This is working as it should, but now I want to extend some functionality to it. I want to keep count of how many times per day the rows has been selected.

Let's say we managed to select 5 restaurants from the query, I want to do something like this for each one of them:

INSERT INTO statistics (date, restaurant_id, number_of_selects) VALUES('{$current_date}', (The restaurants ID), 1) ON DUPLICATE KEY UPDATE number_of_selects = number_of_selects + 1"

What this code does is to increase restaurants number of selects inside the statistics-table. If the row doesn't exist (meaning, it's the first select) it will create the row.

And now to the problem!
What I could do is to loop all the results in PHP and use the second query. However, this is a performance killer. I'm looking for a way to use both these querys at the same time to get the best performance possible.

Edit: I want to keep the data I select (In this case the name of the restaurants).

Thanks in advance,
Tompa

  • 写回答

2条回答 默认 最新

  • duanhuan1147 2014-12-11 21:38
    关注

    I would suggest inserting the result first into a temporary table. Then use this table to update the statistics table, before returning the results to php. This will remove the need for a cursor / loop to iterate over the result set (which is what would kill your performance)

    So something like:

    --Get the restaurants
    CREATE TEMPORARY TABLE IF NOT EXISTS tempTable AS
        (SELECT id, name
        FROM restaurants
        WHERE city='Kalmar'
        LIMIT 100
        )
    
    --Update the statistics
    INSERT INTO statistics (date, restaurant_id, number_of_selects)
    SELECT DATE(), id
    FROM tempTable
    ON DUPLICATE KEY UPDATE number_of_selects = number_of_selects + 1
    
    --Return data to PHP
    SELECT name from tempTable 
    

    I havent checked the syntax etc, but I would expect something like that to work

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作