NOT IN 子查询中的 MySQL“Operand Should Contain 1 Column”错误:解决方案
MySQL 的 NOT IN
子句要求子查询返回单个列。 以下查询会生成“操作数应包含 1 列”错误,因为子查询返回多列:
<code class="language-sql">SELECT * from campaigns WHERE id not in (SELECT e.id_campaign, d.name, d.frequency, d.country, d.referral, d.bid, d.status, COUNT(e.id) AS countcap FROM campaigns d LEFT JOIN served e ON d.id = e.id_campaign WHERE d.status = 'Active' GROUP BY e.id_campaign HAVING countcap < d.frequency)</code>
问题在于在子查询中选择多个字段(例如,e.id_campaign
、d.name
、d.frequency
等)。 NOT IN
需要单列进行比较。
解决方案:使用派生表
为了纠正这个问题,我们可以使用派生表(FROM
子句中的子查询)来隔离相关列:
<code class="language-sql">SELECT * FROM campaigns WHERE id NOT IN (SELECT id_campaign FROM (SELECT e.id_campaign AS id_campaign, d.frequency, e.id FROM campaigns d LEFT JOIN served e ON d.id = e.id_campaign WHERE d.status = 'Active' GROUP BY e.id_campaign HAVING COUNT(e.id) < d.frequency) as subquery);</code>
此修改后的查询使用名为 subquery
的派生表。此内部查询执行原始逻辑,但仅选择 e.id_campaign
(别名为 id_campaign
),确保外部 NOT IN
子句接收单列结果集,从而解决错误。 基于 frequency
和 countcap
的原始过滤逻辑保留在派生表中。
以上是如何修复 MySQL NOT IN 子查询中的'Operand Should Contain 1 Column”错误?的详细内容。更多信息请关注PHP中文网其他相关文章!