我对MySQL数据库的SQL查询:
SELECT `id`, `id_sender`, `id_recipient`, `date_time`, `amount_money`, `id_currency`, `transfer_title`, `authorization_key`, `authorization_status`
FROM `bankapplication_transactions` AS `transaction`
WHERE ((`transaction`.`date_time`
BETWEEN '2019-03-21 08:56:22' AND '2019-04-21 07:56:22'
AND `transaction`.`authorization_status` = 1)
AND (`transaction`.`id_sender` = 3 OR `transaction`.`id_recipient` = 3))
ORDER BY `transaction`.`date_time` ASC
我的结果:
id | id_sender | id_recipient | date_time | ...
2 | 1 | 3 | 2019-04-21 07:51:25 | ...
4 | 4 | 3 | 2019-04-21 07:52:38 | ...
5 | 3 | 4 | 2019-04-21 07:54:39 | ...
我想限制为2,他将返回最后两个结果,但是让它继续由ASC操纵,所以我需要:
id | id_sender | id_recipient | date_time | ...
4 | 4 | 3 | 2019-04-21 07:52:38 | ...
5 | 3 | 4 | 2019-04-21 07:54:39 | ...
我对NodeJS使用Sequelize ORM,所以这是我的控制器:
Transaction.findAll({
where: db.Sequelize.and(
{
date_time: {
[Op.between]: [
getPreviousMonthDate(getTodayDate()),
getTodayDate(),
],
},
authorization_status: setAuthorizationStatus(1),
},
db.Sequelize.or({ id_sender: userId }, { id_recipient: userId }),
),
order: [['date_time', 'ASC']],
})
答案 0 :(得分:0)
您需要按desc排序并限制为2
SELECT `id`, `id_sender`, `id_recipient`, `date_time`, `amount_money`, `id_currency`, `transfer_title`, `authorization_key`, `authorization_status`
FROM `bankapplication_transactions` AS `transaction`
WHERE ((`transaction`.`date_time`
BETWEEN '2019-03-21 08:56:22' AND '2019-04-21 07:56:22'
AND `transaction`.`authorization_status` = 1)
AND (`transaction`.`id_sender` = 3 OR `transaction`.`id_recipient` = 3))
ORDER BY `transaction`.`date_time` desc
lmit 2
答案 1 :(得分:0)
您需要对limit2进行子查询,然后按asc排序
select t.* from (
SELECT `id`, `id_sender`, `id_recipient`, `date_time`, `amount_money`, `id_currency`, `transfer_title`, `authorization_key`, `authorization_status`
FROM `bankapplication_transactions` AS `transaction`
WHERE ((`transaction`.`date_time`
BETWEEN '2019-03-21 08:56:22' AND '2019-04-21 07:56:22'
AND `transaction`.`authorization_status` = 1)
AND (`transaction`.`id_sender` = 3 OR `transaction`.`id_recipient` = 3))
ORDER BY `transaction`.`date_time` desc
lmit 2
) t
order by transaction`.`date_time` ASC