带有“and”条件的Where IN 查询不起作用

问题描述 投票:0回答:1

我正在修复有关过滤器的错误,每个请求可以接收 1 个或多个过滤器。过滤器由 2 个字段组成:attribute_id 和 value。

该应用程序位于 Laravel 中。

过滤器示例:

[
 [
  attribute_id => '33',
  value => 'A',
 ],
 [
  attribute_id => '31',
  value => '2024',
 ],
]

我必须条件一个是

and
,另一个是
or
,问题在于
and
条件

如果只有其中之一存在,我应该不会收到任何结果([]),但如果两者都存在,我应该得到结果,而这就是它失败的地方。我想做这样的事情,但我知道,但没有创建另一个带有别名的内部连接:

select `contacts`.* 
from `contacts` 
inner join `contact_attributes`  on `contact_attributes`.`contact_id` = `contacts`.`id` 
where `contacts`.`company_id` = 7
   and 
   (`contact_attributes`.`attribute_id` = 33 and cast(REPLACE(contact_attributes.value, '"', '') as CHAR) = ('A'))
   and 
   (`contact_attributes`.`attribute_id` = 31 and cast(REPLACE(contact_attributes.value, '"', '') as CHAR) = ('2024'))
sql mysql laravel
1个回答
0
投票

在您的情况下,您在连接表上设置了条件,因此您需要在 JOIN 查询中添加条件

    select `contacts`.* 
from `contacts` 
inner join `contact_attributes`  on `contact_attributes`.`contact_id` = `contacts`.`id` 
AND (`contact_attributes.id`= 33 OR `contact_attributes.id` = 31)
© www.soinside.com 2019 - 2024. All rights reserved.