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中文網其他相關文章!