Home > Database > Mysql Tutorial > Why Does My MySQL `NOT IN` Subquery with Multiple Columns Return 'Operand Should Contain 1 Column'?

Why Does My MySQL `NOT IN` Subquery with Multiple Columns Return 'Operand Should Contain 1 Column'?

Susan Sarandon
Release: 2025-01-12 09:48:43
Original
818 people have browsed it

Why Does My MySQL `NOT IN` Subquery with Multiple Columns Return

MySQL NOT IN "Operation should contain 1 column" error caused by multiple columns in subquery

It is common to encounter the "operand should contain 1 column" error when using the NOT IN clause of a subquery that contains multiple columns. This error arises from the restriction that the NOT IN clause expects the subquery to return only a single column.

In the query provided:

<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 subquery returns eight columns (id_campaign, name, frequency, country, referral, bid, status, and countcap). However, the NOT IN clause requires a single column for comparison.

Solution:

To fix this error, we need to modify the subquery so that it only returns the id_campaign column, which is the column we want to check for non-membership in the main query:

<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

By limiting the subquery results to a single column id_campaign, we eliminate the "operand should contain 1 column" error and ensure that the NOT IN clause performs the comparison correctly. Note that we added an alias subquery to organize the query more clearly. This modified query will only return rows in the campaigns table where id is not in the subquery results.

The above is the detailed content of Why Does My MySQL `NOT IN` Subquery with Multiple Columns Return 'Operand Should Contain 1 Column'?. 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