MySQL NOT IN
查询中的“操作数应包含 1 列”错误
在 MySQL 查询中使用 NOT IN
运算符时,务必确保右侧操作数(子查询)仅包含一列。但是,在某些情况下,我们可能会遇到“操作数应包含 1 列”错误,尤其是在子查询中使用聚合函数(如 COUNT()
)时。
考虑以下查询:
<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>
此查询旨在选择所有不在子查询中的活动,该子查询计算每个活动的已服务条目数,并过滤掉计数小于活动频率的那些条目。但是,由于子查询中存在多列,MySQL 会抛出“操作数应包含 1 列”错误。
解决方案:
为了解决此问题,我们需要修改子查询以确保它只返回 id_campaign
列。以下是修改后的查询版本:
<code class="language-sql">SELECT * FROM campaigns WHERE id NOT IN ( SELECT id_campaign FROM ( SELECT e.id_campaign AS id_campaign, d.frequency, 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 count(e.id) < d.frequency ) AS subquery );</code>
在这个更新后的子查询中,我们只投影 id_campaign
列,从而解决了错误。该查询现在正确地排除了已服务条目计数小于活动频率的活动。
或者,为了更清晰的代码,可以这样改写:
<code class="language-sql">SELECT c.* FROM campaigns c WHERE c.id NOT IN ( SELECT e.id_campaign 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 );</code>
这个版本直接在 NOT IN
子句中选择 id_campaign
,避免了嵌套子查询,使代码更简洁易读。 关键在于 NOT IN
子句右侧的子查询必须只返回单列数据。
以上是为什么我的 MySQL `NOT IN` 查询会抛出'操作数应包含 1 列”错误?的详细内容。更多信息请关注PHP中文网其他相关文章!