Home > Database > Mysql Tutorial > How to Fix the 'Operand Should Contain 1 Column' Error in MySQL's NOT IN Subquery?

How to Fix the 'Operand Should Contain 1 Column' Error in MySQL's NOT IN Subquery?

Barbara Streisand
Release: 2025-01-12 07:13:46
Original
436 people have browsed it

How to Fix the

MySQL "Operand Should Contain 1 Column" Error in NOT IN Subqueries: A Solution

MySQL's NOT IN clause requires the subquery to return a single column. The following query generates the "Operand should contain 1 column" error because the subquery returns multiple columns:

<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>
Copy after login

The problem lies in selecting multiple fields (e.g., e.id_campaign, d.name, d.frequency, etc.) within the subquery. NOT IN expects a single column for comparison.

The Solution: Using a Derived Table

To correct this, we can employ a derived table (a subquery in the FROM clause) to isolate the relevant column:

<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>
Copy after login

This revised query uses a derived table named subquery. This inner query performs the original logic, but only selects e.id_campaign (aliased as id_campaign), ensuring the outer NOT IN clause receives a single-column result set, thus resolving the error. The original filtering logic based on frequency and countcap is retained within the derived table.

The above is the detailed content of How to Fix the 'Operand Should Contain 1 Column' Error in MySQL's NOT IN Subquery?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template