简体   繁体   中英

node.js - Using SQL variables in js query string

So, I am selecting entries from a table and grouping them, but also want to create an index column in the result. Executing this query in MySQL Workbench works, but when I try to execute it on the node.js server there is a parse error and mysql says that the syntax is incorrect.

I am using a raw query and QueryChainer from sequelize .

SET @cnt = 0;
SELECT (@cnt := @cnt + 1) AS id, et.fileName, et.creationDate,
  SUM(COALESCE(et.amountExported, 0)) AS sumExported, 
  SUM(COALESCE(et.amountImported, 0)) AS sumImported,
  (SUM(COALESCE(et.amountExported, 0)) - SUM(COALESCE(et.amountImported, 0))) AS difference
FROM exported_transactions AS et
WHERE (et.creationDate BETWEEN ? AND ?) /* ? is replaced by a date string */
GROUP BY et.fileName

Removing the variable in the sql query and executing it on the node.js server works fine:

SELECT et.fileName, et.creationDate,
  SUM(COALESCE(et.amountExported, 0)) AS sumExported, 
  SUM(COALESCE(et.amountImported, 0)) AS sumImported,
  (SUM(COALESCE(et.amountExported, 0)) - SUM(COALESCE(et.amountImported, 0))) AS difference
FROM exported_transactions AS et
WHERE (et.creationDate BETWEEN ? AND ?) /* ? is replaced by a date string */
GROUP BY et.fileName

Of course, I can do just fine without the "id" column, but I want it there for sorting. Is there a solution to my problem or is there some other way to generate this auto incremented column?

Have you set multipleStatements: true in your database setup object?

If not, remember that with multiple statements the database query passes an array of results (instead of a single results object) to the callback for the query. The "SET" statement will have its own result object in results[0], even though it's not returning any interesting data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM