Use INSERT using SELECT (Node.js and MySql)

1

I need to insert some data into a table, using the following code:

var query = 'INSERT INTO uso (id_usuario, id_tempo) VALUES ((SELECT id FROM usuario WHERE nome='Jose' LIMIT 1), (SELECT id FROM tempo WHERE timestamp=1505530800000 AND nome='dia_de_hoje' LIMIT 1));
INSERT INTO uso (id_usuario, id_tempo)VALUES ((SELECT id FROM usuario WHERE nome='Joao' LIMIT 1), (SELECT id FROM tempo WHERE timestamp=1505530800000 AND nome='dia_de_hoje' LIMIT 1))'

    connection.query(query, function(err, results) {
      if(err) throw err;
      console.log(results);
    });

But I'm getting the following error:

  

Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right   syntax to use near 'INSERT INTO use (userid, time_id)       VALUES ((SELECT id FROM user 'at line 3       at Query.Sequence._packetToError (

When I do this query directly on the server, insert works normally.

    
asked by anonymous 17.09.2017 / 01:36

2 answers

1

The character you are using is not a delimiter of String valid for JavaScript . I made some changes to query also to represent it more easily:

var query = "INSERT INTO uso(id_usuario, id_tempo)\r\n" +
            "SELECT u.id,\r\n" +
            "       (SELECT id\r\n" +
            "          FROM tempo\r\n" +
            "         WHERE timestamp = 1505530800000\r\n" +
            "           AND nome = 'dia_de_hoje'\r\n" +
            "         LIMIT 1)\r\n" +
            "  FROM usuario\r\n" +
            " WHERE nome IN ('Joao', 'Jose')";

connection.query(query, function(err, results) {
  if(err) throw err;
  console.log(results);
});
    
17.09.2017 / 15:49
-4

just use

while c > 1 
select id from tempo;

SET c = c - 1;

end while;
    
17.09.2017 / 02:32