在 MySQL 8 中,in 条件用于多个字段,查询结果为空的排查
1、在 MySQL 8 中,in 条件用于多个字段,查询结果为空。如图1
SELECT `id`, `name`, `email`, `type` FROM `customers` WHERE ( 'name,email' ) IN ( '(\'客户姓名二\',\'44445@163.com\'),(\'客户姓名\',\'44445@163.com\')' ) ORDER BY `id` DESC
2、参考:在 MySQL 8 中,in 条件用于多个字段 查询结果不为空的 SQL 如下
SELECT * FROM `customers` WHERE ( NAME, email ) IN (( '123', '123@outlook.com' ), ( '我是客户姓名33', '1303842899@qq.com' ))
3、参考:在 Laravel 9 中使用原生表达查询时,报错:SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; 调整代码,打印绑定参数,符合预期,没有问题。如图2
$str = ''; foreach ($criteria['whereRawIn'][1] as $key => $customer) { $str .= ($key == 0) ? '(\'' : ',(\''; $str .= implode('\',\'', $customer) . '\')'; } var_dump($criteria['whereRawIn'][0]); var_dump($str); exit;
string(10) "name,email" string(2959) "('客户姓名二','44445@163.com'),('客户姓名','44445@163.com')"
4、调整代码实现如下
$str = ''; foreach ($criteria['whereRawIn'][1] as $key => $customer) { $str .= ($key == 0) ? '(\'' : ',(\''; $str .= implode('\',\'', $customer) . '\')'; } // var_dump('(' . $criteria['whereRawIn'][0] . ')'); // var_dump('(' . $str . ')'); // exit; $builder->whereRaw('? in ?', ['(' . $criteria['whereRawIn'][0] . ')', '(' . $str . ')']);
5、运行时报错:SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘? order by `id` desc’ at line 1 。如图3
6、但是,将报错的 SQL 复制到数据库中,手动执行,执行成功。如图47、调整代码实现如下,运行时报错:SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 2 column(s) 。但是,将报错的 SQL 复制到数据库中,手动执行,执行成功。如图5
$str = ''; foreach ($criteria['whereRawIn'][1] as $key => $customer) { $str .= ($key == 0) ? '(\'' : ',(\''; $str .= implode('\',\'', $customer) . '\')'; } // var_dump('(' . $criteria['whereRawIn'][0] . ')'); // var_dump('(' . $str . ')'); // exit; // $builder->whereRaw('? in ?', ['(' . $criteria['whereRawIn'][0] . ')', '(' . $str . ')']); $builder->whereRaw('(?,?) in (?)', ['name', 'email', $str]); // $builder->whereRaw('( ' . $criteria['whereRawIn'][0] . ' ) in (?)', [$str]);
8、最终决定放弃此 SQL,调整为另外一种 SQL 格式。代码实现如下,生成 SQL 如下,程序运行时不再报错,查询结果符合预期。如图6
foreach ($criteria['names_emails'] as $customer) { $builder->orWhere(function ($query) use ($customer) { $query->where('name', $customer[0]) ->where('email', $customer[1]); }); }
SELECT `id`, `name`, `email`, `type` FROM `customers` WHERE ( `name` = '客户姓名二' AND `email` = '客户姓名二' ) OR ( `name` = '客户姓名' AND `email` = '客户姓名' ) ORDER BY `id` DESC
近期评论