Use INSERT using SELECT (Node.js and Mysql)

Asked

Viewed 313 times

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 (id_usuario, id_tempo) VALUES ((SELECT id FROM usuar' at line 3 At Query.Sequence. _packetToError (

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

  • 1

    Try using an assignment, for example SELECT id as id_usuario FROM usuario...

2 answers

1


The character you are using is not a delimiter of String valid for the JavaScript. I made some modifications 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);
});

-4

just use

while c > 1 
select id from tempo;

SET c = c - 1;

end while;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.