【发布时间】:2018-06-27 18:44:09
【问题描述】:
有两个表:Books,列出可用书籍,BorrowedBooks,列出当前借阅的书籍。我只想检索当前可用(未借阅)的书籍,提供分页和总数。
我会使用 Sequelize 提供的方法findAndCountAll,它真的很容易使用并且可以完成大部分工作,但是它不能正常工作。我尝试了以下代码,使用findAll 方法,它可以正常工作。
Books.findAll({
where: { '$BorrowedBooks.bookId$': null },
include: [BorrowedBooks]
}).then(...).catch(...);
然后我将方法改为findAndCountAll,以获取元素的总数并提供分页。
Books.findAndCountAll({
where: { '$BorrowedBooks.bookId$': null },
include: [BorrowedBooks],
offset: offset,
limit: limit,
distinct: true
}).then(...).catch(...);
此版本产生错误Unknown column 'BorrowedBooks.bookId' in 'where clause'。
编辑
生成的带有不起作用的代码的查询如下:
SELECT
`books`.*,
`borrowedBooks`.`bookId` AS `borrowedBooks.bookId`,
`borrowedBooks`.`userId` AS `borrowedBooks.userId`,
FROM
(SELECT
`books`.`id`,
`books`.`title`,
`books`.`author`,
`books`.`isbn`
FROM
`books` AS books`
WHERE
(SELECT
`bookId`
FROM
`borrowedBooks`
WHERE
(`borrowedBooks`.`bookId` = `books`.`id`
AND `borrowedBooks`.`bookId` IS NULL)
LIMIT 1) IS NOT NULL
LIMIT 0 , 10) AS `books`
INNER JOIN
`borrowedBooks` ON `books`.`id` = `borrowedBooks`.`bookId`
AND `borrowedBooks`.`bookId` IS NULL;
如果我直接写下查询,我会这样做:
SELECT * FROM `books`
LEFT OUTER JOIN `borrowedBooks` ON `books`.`id` = `borrowedBooks`.`bookId`
WHERE `borrowedBooks`.`bookId` IS NULL
我认为错误是由于 Sequelize 使用的 INNER JOIN 造成的。
【问题讨论】:
标签: mysql node.js sequelize.js