如何在NodeJS中使用MySQL @ Session变量?

时间:2019-05-12 13:49:11

标签: mysql node.js express sequelize.js

我正在创建一个旨在显示一些图表的应用程序。我使用Express Framework(NodeJS)和Sequelize构建了mysql数据库连接器。我差不多完成了,但是我对此查询感到困惑,因为查询要求我使用@会话变量。

以下代码是我使用的查询

SELECT 
drive_id, officer_id, officer_name, 
vehicle_serial_number, 
FORMAT(ROUND(ROUND(SUM(TIME_TO_SEC(TIMEDIFF(finish_time, start_time)) / 60)) / 3), 1) AS average_cycle_time,
ROUND(SUM(TIME_TO_SEC(TIMEDIFF(finish_time, start_time)) / 60)) AS cycle_minute,
COUNT(drive_id) AS amount_of_cycle, 
drive_rank,
cycle_date
FROM (
SELECT
c.drive_id,
o.id AS officer_id,
v.serial_number AS vehicle_serial_number,
c.start_time, c.finish_time,
c.date AS cycle_date,
@drive_rank := IF(@current_drive = o.name, @drive_rank + 1, 1) AS drive_rank, 
@current_drive := o.name AS officer_name
FROM cycles c
INNER JOIN drives d ON d.id = c.drive_id
INNER JOIN officers o ON o.id = d.officer_id
INNER JOIN vehicles v ON v.id = d.vehicle_id
WHERE c.date = '2019-05-01'
ORDER BY c.drive_id ASC
) ranked
WHERE ranked.drive_rank <= 3
GROUP BY drive_id, officer_id;

该结果查询实际上是有效的,但是@drive_rank无法运行。有没有办法让我执行该查询,或者我必须重新考虑以重新安排查询?谢谢。

1 个答案:

答案 0 :(得分:0)

好的,我已经回答了我自己的问题,哈哈。如果以后有人遇到相同的问题,我想分享答案,那就是:

  1. 如果要使用MySQL Sequelize会话变量,则不能使用@。使用标准的mysql
  2. 然后依次执行两次查询

对于我来说,它会起作用的,祝你好运