我正在尝试计算上次用户登录和现在之间的评论数量。我正在使用knex,但是首先尝试在MYSQL中没有SET的一个语句中使用它。
这是我正在寻找的但它没有返回正确的COUNT。声明似乎没有在WHERE BETWEEN语句中使用@lastlogin变量,但我无法弄清楚原因。
SELECT Count(*), @lastlogin := (SELECT DATE(userLastLogin) FROM users WHERE users.UID = 50) AS login
FROM reviews
RIGHT JOIN schools on schools.SID = reviews.schoolID
WHERE reviews.dateCreated BETWEEN @lastlogin AND NOW()
AND reviews.active = 1;
如果我使用它,它可以工作。
SET @lastlogin = (SELECT DATE(userLastLogin) FROM users WHERE users.UID = 50);
SELECT Count(*)
FROM reviews
RIGHT JOIN schools on schools.SID = reviews.schoolID
WHERE reviews.dateCreated BETWEEN @lastlogin AND NOW()
AND reviews.active = 1
如果我在BETWEEN中明确地写了一个日期,那就有效了。
为什么它不能在SELECT中定义变量?
如果我只是使用MYSQL就可以了,但我需要在SELECT for Knex.js中设置变量。
答案 0 :(得分:1)
为什么需要用户变量?也许knex.js不支持其中任何一个......
SELECT Count(*)
FROM reviews
RIGHT JOIN schools on schools.SID = reviews.schoolID
WHERE reviews.dateCreated BETWEEN (SELECT DATE(userLastLogin)
FROM users
WHERE users.UID = 50) AND NOW()
AND reviews.active = 1;
或者如果由于某种原因确实需要用户变量......也许..
SELECT Count(*), @LastLogin
FROM reviews
RIGHT JOIN schools on schools.SID = reviews.schoolID
CROSS JOIN (SELECT @LastLogin:=(SELECT DATE(userLastLogin)
FROM users
WHERE users.UID = 50))
WHERE reviews.dateCreated BETWEEN @LastLogin AND NOW()
AND reviews.active = 1;
回答你的问题虽然是两次
cross join (Select @LastLogin:=Now())