gpt4 book ai didi

mysql - 如何在带有可选包含的 where 子句中使用运算符?

转载 作者:可可西里 更新时间:2023-11-01 07:06:51 24 4
gpt4 key购买 nike

我有以下模型:

AuthorModel.hasMany(BookModel);
BookModel.belongsTo(AuthorModel);

有些作者没有书。

我想选择一位作者,其姓名或其中一本书的标题与搜索字符串匹配。

我可以通过以下语句实现这一点,但仅适用于在 BookModel 中有书籍的作者

       Author.findOne({
include: [{
model: Book,
where: {
[Op.or]: [
{'$author.name$': 'search string'},
{ title: 'search string'}
]
},
}]
})

这或多或少给了我以下 mysql 查询:

SELECT 
`author`.`name`,
`book`.`title`
FROM `author` INNER JOIN `book`
ON `author`.`id` = `book`.`authorId`
AND ( `author`.`name` = 'search string' OR `book`.`title` = 'search string');

这里的问题是,如果作者没有书,那么结果是空的。即使有符合搜索条件的作者。

我尝试将 include 设置为 required: false,这给出了一个 left outer join。在那种情况下,我会得到一些不匹配的结果。省略了 where 子句。

我必须如何更改我的 sequelize 查询,或者什么是正确的 mysql 查询?

最佳答案

MySql 查询应该是这样的

SELECT 
`author`.`name`,
`book`.`title`
FROM `author` LEFT JOIN `book`
ON `author`.`id` = `book`.`authorId`
WHERE ( `author`.`name` = 'search string' OR `book`.`title` = 'search string')

注意这里的过滤条件是在 WHERE 而不是 JOIN ... ON 子句的一部分

基于 Top level where with eagerly loaded models 的示例你的 squizzle 查询可能应该是这样的

Author.findOne({
where: {
[Op.or]: [
{'$author.name$': 'search string'},
{ '$Book.title$': 'search string'}
]
},
include: [{
model: Book,
required: false
}]})

关于mysql - 如何在带有可选包含的 where 子句中使用运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47263577/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com