一个表中的MySQL SELECT和另一个表中的INSERT - 性能

时间:2014-02-24 07:00:40

标签: mysql performance node.js

情况是:在一个http GET请求中,我需要从一个表中选择我需要的信息并发送到客户端,同时我需要检索用户IP并插入到数据库中。我正在使用Node.js进行此实验。

事情是:有没有办法让这两个行动在一起?或者我必须连接并进行两个单独的查询?有没有办法渲染页面并在后台执行其他INSERT操作?什么是最快的选择?

app.get('/', function({
    connect.query("SELECT column1, column2 FROM table;", function(err, ... 
        render("index", ...);
    });

    connect.query("INSERT INTO table2 SET ip=11111111;");
});

3 个答案:

答案 0 :(得分:2)

您可以使存储过程执行此操作

基本上这些是两个不同的操作,但是在存储过程中执行它可能会让您确信它肯定会发生,您可以将IP地址作为参数传递到存储过程中,这也可以避免任何对性能的担忧。作为db的代码负责插入,请记住,任何未插入表或变量的选择都会生成一个结果集供您使用,希望这会有所帮助。

DELIMITER $
CREATE PROCEDURE AddIPandReturnInfo 
(
    @IPAddress varchar(20)
)
BEGIN
    INSERT INTO Yourtable (IPAddress);

    SELECT   *   FROM    Tablename;
END $
DELIMITER ;

答案 1 :(得分:2)

@skv建议的过程方法很好但是你必须在执行读操作之前等待写操作并最终将结果返回给用户。

我会争论另一种方法。

  • 在内部以类似数组或列表的方式对ip-address和时间戳进行排队。
  • 从数据库中读取并将结果返回给用户
  • 创建一个后台作业,该作业将对内部数组进行半字节并执行插入

这有几个好处

  • 用户更快地获得结果
  • 如果以突发方式调用系统,则可以稍后进行写入
  • 写入可以分批进行数十或数百次插入,减少了写入一行所需的时间。

答案 2 :(得分:1)

好吧,我假设你正在使用这个模块https://github.com/felixge/node-mysql

  

MySQL 协议是顺序,然后,要对mysql执行并行查询,您需要多个连接。您可以使用Pool来管理连接。(内置在模块中)

示例:

var mysql = require('mysql');
var pool = mysql.createPool({
    host: 'example.org',
    user: 'bob',
    password: 'secret',
    connectionLimit: 5 // maximum number of connections to create at once **10 by default**
});
app.get('/', function (req, res) {
    // get a connection from the pool //async
    pool.getConnection(function (err, connection) {
        // Use the connection
        connection.query('SELECT something FROM table1', function (err, rows) {
            // Do somethig whith the mysql_response and end the client_response
            res.render("index", {...
            });
            connection.release();
            // Don't use the connection here, it has been closed.
        });
    });
    //async
    var userIp = req.connection.remoteAddress || req.headers['x-forwarded-for'] || null;
    if (userIp) {
        // get a connection from the pool again
        pool.getConnection(function (err, connection) {
            // Use the connection
            connection.query('INSERT INTO table2 SET ip=?', [userIp], function (err, rows) {
                // And done with the insert.
                connection.release(); // Conn Close.
            });
        });
    }
});