MojioMS
MojioMS

Reputation: 1693

how to use mysql's FIND_IN_SET in nodejs?

I have a simple mysql datatable like this:

users:
user_id score
1          0
2         20
3       1430
4        820
5        170

Im using the following mysql query to get the rank of a user with a certain user_id:

SELECT FIND_IN_SET( score, (
                    SELECT GROUP_CONCAT( score
                        ORDER BY score DESC ) 
                    FROM users )
                ) AS rank
                  FROM users WHERE user_id = 4

and in my mysql it returns me correctly

rank
2

because user_id=4 has the 2nd highest score here.

But how does the corresponding query look like in nodejs? My copy-paste code returns an error:

var query = connection.query('SELECT FIND_IN_SET( score, (
                    SELECT GROUP_CONCAT( score
                        ORDER BY score DESC ) 
                    FROM users )
                ) AS rank
                  FROM users WHERE user_id = 4', function(err, result){
    console.log(err);
});

with the error:

    var query = connection.query('SELECT FIND_IN_SET( score, (
                                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Unexpected token ILLEGAL

Upvotes: 0

Views: 533

Answers (1)

christophetd
christophetd

Reputation: 3874

You can't have multiline strings in JavaScript without escaping the line returns or using ES6 template. Try

var query = connection.query("SELECT FIND_IN_SET( score, (\
                SELECT GROUP_CONCAT( score\
                    ORDER BY score DESC ) \
                FROM users )\
            ) AS rank\
              FROM users WHERE user_id = 4", function(err, result){
console.log(err);
});

Upvotes: 1

Related Questions