合并联接和where子句

时间:2019-07-19 15:29:55

标签: node.js sequelize.js where-clause

我有以下要求:

select bo.id, bo.code, bo.title from books bo, Chapters c, Blocks bk 
where (bo.id=c.id and c.idChapter=bk.idChapter) and ( (bo.title like '%intermit%') or (bk.content like '%intermit%') ) 
group by bo.code  
order by bo.code asc

我尝试使用Sequelize翻译请求:

db.books.findAll({
  attributes: ['id', 'title', 'code'],
  include: [
    {
      model: db.chapters,
      as: 'Chapters',
      attributes: [ 'id', 'idChapter' ],
      include: [
        {
          model: db.blocks,
          as: 'Blocks',
          attributes: ['content', 'idBlock'],
          where: {content: {[Op.like]: ('%'+criteria+'%') }}
        }
      ]
    }
  ],
  where: {title: {[Op.like]: ('%'+criteria+'%') }},
  group: ['code'],
  order: [['code', 'ASC']]
})

由Sequelize生成的请求并不完全相同。它使用join而不是where子句,但这不是问题。

问题是关于字段blocks.content的where子句。低于Sequelize生成的请求(安静简化,易于阅读)。

SELECT bo.id, bo.title, bo.code
FROM books AS bo 
LEFT OUTER JOIN ( Chapters AS c INNER JOIN Blocks AS bk ON c.idChapter = bk.idChapter AND bk.content LIKE '%intermit%') ON bo.id = c.id
WHERE bo.title LIKE '%intermit%' GROUP BY bo.code ORDER BY bo.code ASC;

与字段where有关的content子句放在inner子句的内部。它应位于主要where子句的外部。对于该请求,结果是不同的,而不是预期的结果。

我尝试用单个where条款修改代码:

    where: { [Op.or]: [ {title: {[Op.like]: ('%'+criteria+'%')}}, {content: {[Op.like]: ('%'+criteria+'%')}} ] },

但是它无法识别字段content,因为Sequelize希望在表books中找到它。

我该如何解决我的问题?

0 个答案:

没有答案