3

这个逻辑有什么问题?

var selectString = 'SELECT EXISTS(SELECT 1 FROM users WHERE user="'+username+'")';

var queryUserExists = connection.query(selectString);
var resultsLength = queryUserExists._results.length;

console.log(queryUserExists);

if(resultsLength > 0){
   socket.write("fail user already exists"+"\r\n");

} else {
    console.log('insert=');
    var query = connection.query (
        'INSERT INTO users '+
        'SET user = ?, password = ?, token = ?',
        [username, password, token]
    );

    socket.write("success"+"\r\n");
}

resultsLength 始终返回零。使用此查询的正确方法是什么?

返回对象:

sql: 'SELECT 1 FROM users WHERE user = \'a new user is my name\' ORDER BY user LIMIT 1',
typeCast: true,
nestTables: false,
_resultSet: null,
_results: [],
_fields: [],
_index: 0,
_loadError: null }
4

2 回答 2

4

正确的代码:感谢https://stackoverflow.com/users/722783/mahmoud-gamal优化了数据库查询!

connection.query("SELECT 1 FROM users WHERE user = '"+username+"' ORDER BY user LIMIT 1", function (error, results, fields) {
if (error) {
    console.log(error);
    socket.write("fail internal error"+"\r\n");
}
if (results.length  > 0) {
    console.log('fail');
    socket.write("fail user already exists"+"\r\n");

} else {


        console.log('insert');
        var query = connection.query (
            'INSERT INTO users '+
            'SET user = ?, password = ?, token = ?',
            [username, password, token]
        );

        socket.write("success"+"\r\n");


}

console.log(results);
});
于 2013-01-10T11:02:18.540 回答
2

试试这个:

SELECT 1
FROM users
WHERE EXISTS (SELECT 1 
              FROM users 
              WHERE user = 'username')
ORDER BY user
LIMIT 1;

或者:为什么不:

SELECT 1
FROM users
WHERE user = 'username'
ORDER BY user
LIMIT 1;

注意:

ORDER BY user
LIMIT 1;

只是为了性能。

于 2013-01-10T09:10:14.910 回答