NOT IN
具有聚合函數的子查詢中的 MySQL「運算元應包含 1 列」錯誤
在 MySQL 中使用 NOT IN
子查詢需要仔細注意列計數。 當子查詢使用 COUNT()
等聚合函數傳回多列時,會出現一個常見錯誤「運算元應包含 1 列」。 MySQL 的 NOT IN
運算子需要單列比較。
根本原因:
此錯誤源自於主查詢和子查詢傳回的列數不符。 包含聚合函數的 NOT IN
子查詢會產生包含多個欄位的結果集,與主查詢的 id
子句中的單列 WHERE
衝突。
範例:
考慮這個有問題的查詢:
<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 < p>The intention is to select campaigns *not* included in the subquery's results. The subquery, however, returns eight columns, causing the "Operand should contain 1 column" error because `NOT IN` expects a single-column comparison against the `id` column in the `campaigns` table.</p><p>**Resolution:**</p><p>The solution involves restructuring the subquery to return only the `id_campaign` column:</p><pre class="brush:php;toolbar:false"><code class="language-sql">SELECT * FROM campaigns WHERE 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) < </code>
Alternatively, for situations requiring multiple columns, use `EXISTS` or `NOT EXISTS` for a more efficient and accurate solution:
<code class="language-sql">SELECT * FROM campaigns c WHERE NOT EXISTS ( SELECT 1 FROM campaigns d INNER JOIN served e ON d.id = e.id_campaign WHERE d.id = c.id AND d.status = 'Active' AND COUNT(e.id) < </code>
This revised approach avoids the column count mismatch and provides a cleaner solution for scenarios involving aggregate functions within subqueries used with `NOT IN`.
以上是為什麼我的 MySQL `NOT IN` 查詢使用 `COUNT()` 會導致「運算元應包含 1 列」錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!