Error 1241 operand should contain 1 column s sql

Learn how to fix MySQL error operand should contain 1 column(s)

The error Operand should contain 1 column(s) is most likely caused by a subquery that’s returning more than one column.

Here’s a typical SELECT query that causes this error:

SELECT column_one, 
    (SELECT column_two, column_three FROM table_two) 
  FROM table_one;

The above subquery returns column_two and column_three, so MySQL throws the Operand should contain 1 column(s) error.

Most often, you only need to check your subquery and make sure that it returns only one column.

If you need more guidance on how to fix this MySQL error, then you may read the next section.

How to fix Operand should contain 1 column(s) error

To illustrate an example, imagine you have two tables that have related data named members and pets.

The members table contain the first_name of people who have pets as shown below:

+----+------------+----------------+
| id | first_name | country        |
+----+------------+----------------+
|  1 | Jessie     | United States  |
|  2 | Ann        | Canada         |
|  3 | Joe        | Japan          |
|  4 | Mark       | United Kingdom |
|  5 | Peter      | Canada         |
+----+------------+----------------+

While the pets table contain the owner and the species column as follows:

+----+--------+---------+------+
| id | owner  | species | age  |
+----+--------+---------+------+
|  1 | Jessie | bird    |    2 |
|  2 | Ann    | duck    |    3 |
|  3 | Joe    | horse   |    4 |
|  4 | Mark   | dog     |    4 |
|  5 | Peter  | dog     |    5 |
+----+--------+---------+------+

The first_name and the owner columns are related, so you may use a subquery to display data from both tables like this:

SELECT `first_name` AS `owner_name`, 
  (SELECT `species`, `age` 
    FROM pets WHERE pets.owner = members.first_name) 
  FROM members;

However, the above SQL query is wrong, and it will throw an error like this:

ERROR 1241 (21000): Operand should contain 1 column(s)

This is because MySQL expects the subquery to return only one column, but the above subquery returns two.

To fix the error, you may create two subqueries with each subquery returning only one column as in the following SELECT statement:

SELECT `first_name` AS `owner_name`, 
  (SELECT `species` 
    FROM pets WHERE pets.owner = members.first_name) AS `species`,
  (SELECT `age` 
    FROM pets WHERE pets.owner = members.first_name) AS `age`  
  FROM members;

While the above query works, it will throw another error once the subquery returns more than one row.

Let’s add another pet that’s owned by “Jessie” to the pets table as shown below:

+----+--------+---------+------+
| id | owner  | species | age  |
+----+--------+---------+------+
|  1 | Jessie | bird    |    2 |
|  2 | Ann    | duck    |    3 |
|  3 | Joe    | horse   |    4 |
|  4 | Mark   | dog     |    4 |
|  5 | Peter  | dog     |    5 |
|  6 | Jessie | cat     |    4 |
+----+--------+---------+------+

Now the subqueries will return two species and age rows for “Jessie”, causing another related error:

mysql> SELECT `first_name` AS `owner_name`, 
   ->   (SELECT `species` 
   ->     FROM pets WHERE pets.owner = members.first_name) 
   ->   FROM members;
ERROR 1242 (21000): Subquery returns more than 1 row

To properly fix the error, you need to replace the subquery with a JOIN clause:

SELECT `first_name` AS `owner_name`, `species`, `age`
  FROM members JOIN pets 
  ON members.first_name = pets.owner;

Subqueries can be used to replace JOIN clauses only when you need to SELECT data from one table, but you need to filter the result by another table column.

For example, maybe you have some owner names in the pets table that aren’t recorded in the members table. You can use a subquery in the WHERE clause to display rows in the pets table that are also recorded in the members table.

Here’s an example of using a subquery in the WHERE clause:

SELECT `owner`, `species`, `age` 
  FROM pets 
  WHERE `owner` IN (SELECT `first_name` FROM members);

Without using a subquery, you need to JOIN the table as shown below:

SELECT `owner`, `species`, `age` 
  FROM pets JOIN members 
  ON pets.owner = members.first_name;

The two queries above will produce the same result set.

And that’s how you can fix the Operand should contain 1 column(s) error in MySQL.

You need to check your subquery before anything else when you encounter this error.

Содержание

  1. How to fix MySQL operand should contain 1 column(s) error
  2. How to fix Operand should contain 1 column(s) error
  3. Level up your programming skills
  4. About
  5. How to fix MySQL operand should contain 1 column(s) error
  6. How to fix Operand should contain 1 column(s) error
  7. Level up your programming skills
  8. About

How to fix MySQL operand should contain 1 column(s) error

Posted on Oct 06, 2021

Learn how to fix MySQL error operand should contain 1 column(s)

The error Operand should contain 1 column(s) is most likely caused by a subquery that’s returning more than one column.

Here’s a typical SELECT query that causes this error:

The above subquery returns column_two and column_three , so MySQL throws the Operand should contain 1 column(s) error.

Most often, you only need to check your subquery and make sure that it returns only one column.

If you need more guidance on how to fix this MySQL error, then you may read the next section.

How to fix Operand should contain 1 column(s) error

To illustrate an example, imagine you have two tables that have related data named members and pets .

The members table contain the first_name of people who have pets as shown below:

While the pets table contain the owner and the species column as follows:

The first_name and the owner columns are related, so you may use a subquery to display data from both tables like this:

However, the above SQL query is wrong, and it will throw an error like this:

This is because MySQL expects the subquery to return only one column, but the above subquery returns two.

To fix the error, you may create two subqueries with each subquery returning only one column as in the following SELECT statement:

While the above query works, it will throw another error once the subquery returns more than one row.

Let’s add another pet that’s owned by “Jessie” to the pets table as shown below:

Now the subqueries will return two species and age rows for “Jessie”, causing another related error:

To properly fix the error, you need to replace the subquery with a JOIN clause:

Subqueries can be used to replace JOIN clauses only when you need to SELECT data from one table, but you need to filter the result by another table column.

For example, maybe you have some owner names in the pets table that aren’t recorded in the members table. You can use a subquery in the WHERE clause to display rows in the pets table that are also recorded in the members table.

Here’s an example of using a subquery in the WHERE clause:

Without using a subquery, you need to JOIN the table as shown below:

The two queries above will produce the same result set.

And that’s how you can fix the Operand should contain 1 column(s) error in MySQL.

You need to check your subquery before anything else when you encounter this error.

Level up your programming skills

I’m sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I’ll send new stuff straight into your inbox!

About

Nathan Sebhastian is a software engineer with a passion for writing tech tutorials.
Learn JavaScript and other web development technology concepts through easy-to-understand explanations written in plain English.

Источник

How to fix MySQL operand should contain 1 column(s) error

Posted on Oct 06, 2021

Learn how to fix MySQL error operand should contain 1 column(s)

The error Operand should contain 1 column(s) is most likely caused by a subquery that’s returning more than one column.

Here’s a typical SELECT query that causes this error:

The above subquery returns column_two and column_three , so MySQL throws the Operand should contain 1 column(s) error.

Most often, you only need to check your subquery and make sure that it returns only one column.

If you need more guidance on how to fix this MySQL error, then you may read the next section.

How to fix Operand should contain 1 column(s) error

To illustrate an example, imagine you have two tables that have related data named members and pets .

The members table contain the first_name of people who have pets as shown below:

While the pets table contain the owner and the species column as follows:

The first_name and the owner columns are related, so you may use a subquery to display data from both tables like this:

However, the above SQL query is wrong, and it will throw an error like this:

This is because MySQL expects the subquery to return only one column, but the above subquery returns two.

To fix the error, you may create two subqueries with each subquery returning only one column as in the following SELECT statement:

While the above query works, it will throw another error once the subquery returns more than one row.

Let’s add another pet that’s owned by “Jessie” to the pets table as shown below:

Now the subqueries will return two species and age rows for “Jessie”, causing another related error:

To properly fix the error, you need to replace the subquery with a JOIN clause:

Subqueries can be used to replace JOIN clauses only when you need to SELECT data from one table, but you need to filter the result by another table column.

For example, maybe you have some owner names in the pets table that aren’t recorded in the members table. You can use a subquery in the WHERE clause to display rows in the pets table that are also recorded in the members table.

Here’s an example of using a subquery in the WHERE clause:

Without using a subquery, you need to JOIN the table as shown below:

The two queries above will produce the same result set.

And that’s how you can fix the Operand should contain 1 column(s) error in MySQL.

You need to check your subquery before anything else when you encounter this error.

Level up your programming skills

I’m sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I’ll send new stuff straight into your inbox!

About

Nathan Sebhastian is a software engineer with a passion for writing tech tutorials.
Learn JavaScript and other web development technology concepts through easy-to-understand explanations written in plain English.

Источник

Всем привет! Выходит это ошибка при вставке в таблицу данные.
Этот же код нормально работает для триггера Before Update, а для Before Insert выдает ошибку, типа много чем одной строки как я понял.
Вот мой код:

DROP TRIGGER IF EXISTS `InsertBuildingAnalysis`;
CREATE TRIGGER `InsertBuildingAnalysis` BEFORE INSERT ON `MDepartments` FOR EACH ROW BEGIN

  DECLARE population INT;
  DECLARE normative, isnornamtive INT;
  DECLARE locality VARCHAR(1256);
  DECLARE loc_dis_id int;
  DECLARE loc_isCenter int;
  DECLARE sub_pop int;
  DECLARE sub_cpop int;
  DECLARE dis_pop int;

  SET population = (SELECT new_fnc(new.ParentId));
  SET locality = (SELECT * FROM Localities WHERE Localities.Id = new.LocalityId);
  SET loc_dis_id = (SELECT Localities.DistrictId FROM Localities WHERE Localities.Id = new.LocalityId);
  SET loc_isCenter = (SELECT Localities.IsCenter from Localities WHERE Localities.Id = new.LocalityId);
  SET sub_pop = (SELECT new_fnc2(new.SubRegionId));
  SET sub_cpop = (SELECT new_fnc3(new.SubRegionId));
  SET dis_pop = (SELECT new_fnc4(loc_dis_id));

  IF (new.TypeId = 4 ) THEN
    IF (population < 50) THEN
      SET new.Normative = 0;
      SET new.IsNormativePositive = 1;
    ELSEIF (population > 8000) THEN
      SET new.Normative = 0;
      SET new.IsNormativePositive = 0;
    ELSE
      SET new.Normative = 1;
    END IF;
  ELSEIF (new.TypeId = 3) THEN
    IF (population < 800) THEN
      SET  new.Normative = 1;
      SET  new.IsNormativePositive = 1;
    ELSEIF (population > 2000) THEN
      SET new.Normative = 0;
      SET new.IsNormativePositive = 0;
    ELSE
      SET new.Normative = 1;
    END IF ;
  ELSEIF (new.TypeId = 2) THEN
    IF (population > 800 && population <= 2000) THEN
      SET new.Normative = 2;
    ELSEIF (population > 2000 ) THEN
      SET new.Normative = 1;
    ELSE
      SET new.Normative = 0;
      SET new.IsNormativePositive = 1;
    END IF;
  ELSEIF (new.TypeId = 57) THEN
    IF(population < 10000) THEN
      SET new.Normative = 0;
      SET new.IsNormativePositive = 1;
    ELSE
      SET new.Normative = 1;
    END IF;
  ELSEIF (new.TypeId = 26)THEN
    IF (!locality) THEN
      SET new.Normative = -1;
    ELSEIF (loc_isCenter != 1) THEN
      SET new.Normative = -2;
    ELSE
      SET new.Normative = 1;
    END IF;
  ELSEIF (new.TypeId = 35) THEN
    SET  population = sub_pop + sub_cpop;
    IF(population >= 100000) THEN
      SET new.Normative = 1;
    ELSE
      SET new.Normative = 0;
      SET new.IsNormativePositive = 1;
    END IF;
  ELSEIF (new.TypeId = 27) THEN
    SET population = dis_pop;
    IF(population > 5000) THEN
    SET new.Normative = 1;
    ELSE
      SET new.Normative = 0;
      SET new.IsNormativePositive = 1;
    END IF;
  ELSEIF (new.TypeId = 25) THEN
    SET new.Normative = 1;
  END IF;
END;

Не знаю как исправить! Ваши варианты пож-а!

sql – MySQL error 1241: Operand should contain 1 column(s)

Syntax error, remove the ( ) from select.

insert into table2 (name, subject, student_id, result)
select name, subject, student_id, result
from table1;

Just remove the ( and the ) on your SELECT statement:

insert into table2 (Name, Subject, student_id, result)
select Name, Subject, student_id, result
from table1;

sql – MySQL error 1241: Operand should contain 1 column(s)

Another way to make the parser raise the same exception is the following incorrect clause.

SELECT r.name
FROM roles r
WHERE id IN ( SELECT role_id ,
                     system_user_id
                 FROM role_members m
                 WHERE r.id = m.role_id
                 AND m.system_user_id = intIdSystemUser
             )

The nested SELECT statement in the IN clause returns two columns, which the parser sees as operands, which is technically correct, since the id column matches values from but one column (role_id) in the result returned by the nested select statement, which is expected to return a list.

For sake of completeness, the correct syntax is as follows.

SELECT r.name
FROM roles r
WHERE id IN ( SELECT role_id
                 FROM role_members m
                 WHERE r.id = m.role_id
                 AND m.system_user_id = intIdSystemUser
             )

The stored procedure of which this query is a portion not only parsed, but returned the expected result.

Related posts on MySQL Error :

  • MySQL error code: 1175 during UPDATE in MySQL Workbench
  • MySQL Error Operand should contain 1 column
  • MySQL ERROR 1290 (HY000) –secure-file-priv option
  • mysql error 1364 Field doesnt have a default values
  • sql – MySQL Error 1264: out of range value for column
  • sql – MySQL error: key specification without a key length
  • mySQL Error 1040: Too Many Connection
  • php – mysql error TYPE=MyISAM

547 votes

3 answers

Get the solution ↓↓↓

I am trying to Insert data from a table1 into table2

insert into table2(Name,Subject,student_id,result)
select (Name,Subject,student_id,result)
from table1;

Key for table2 is student_id.

Assume that there are not any duplicates.

I get the error:MySQL error 1241: Operand should contain 1 column(s)

There are only four columns in table2.

2022-04-22

Write your answer


445

votes

Answer

Solution:

Syntax error, remove the( ) fromselect.

insert into table2 (name, subject, student_id, result)
select name, subject, student_id, result
from table1;


492

votes

Answer

Solution:

Just remove the( and the) on your SELECT statement:

insert into table2 (Name, Subject, student_id, result)
select Name, Subject, student_id, result
from table1;


251

votes

Answer

Solution:

Another way to make the parser raise the same exception is the following incorrect clause.

SELECT r.name
FROM roles r
WHERE id IN ( SELECT role_id ,
                     system_user_id
                 FROM role_members m
                 WHERE r.id = m.role_id
                 AND m.system_user_id = intIdSystemUser
             )

The nestedSELECT statement in theIN clause returns two columns, which the parser sees as operands, which is technically correct, since the id column matches values from but one column (role_id) in the result returned by the nested select statement, which is expected to return a list.

For sake of completeness, the correct syntax is as follows.

SELECT r.name
FROM roles r
WHERE id IN ( SELECT role_id
                 FROM role_members m
                 WHERE r.id = m.role_id
                 AND m.system_user_id = intIdSystemUser
             )

The stored procedure of which this query is a portion not only parsed, but returned the expected result.


Share solution ↓

Additional Information:

Date the issue was resolved:

2022-04-22

Link To Source

Link To Answer
People are also looking for solutions of the problem: property [id] does not exist on this collection instance.

Didn’t find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.


Similar questions

Find the answer in similar questions on our website.

5 ответов

Проблема заключается в том, что ваш внутренний запрос возвращает два столбца. Измените свой запрос, например

UPDATE ADRESSEN
SET EMAIL = 0
WHERE ID = (SELECT ID
FROM EIGENSCHAFTEN WHERE Kategorie = "BOUNCE" 
GROUP BY ID
HAVING COUNT(ID) = 1)

Это должно сработать.

У меня есть еще одно предложение: вы уверены, что ваш внутренний запрос всегда будет возвращать одну строку?
Если вы хотите установить EMAIL со значением 0 для нескольких идентификаторов, возвращаемых внутренним запросом, я бы рекомендовал использовать «IN» вместо «=».

sak
14 март 2012, в 18:53

Поделиться

В вашем подзапросе содержатся два столбца. Попробуйте следующее:

UPDATE ADRESSEN
SET EMAIL = 0
WHERE ID = (SELECT ID
FROM EIGENSCHAFTEN WHERE Kategorie = "BOUNCE" 
GROUP BY ID
HAVING COUNT(ID) = 1)

Я удалил COUNT(ID), поэтому вы выбираете только идентификатор и вместо этого помещаете его в предложение HAVING.

Кроме того, если вы не уверены, что этот запрос никогда не вернет более одной строки, вам нужно иметь дело с возможностью дублирования. Либо измените на WHERE ID IN вместо WHERE ID =, либо ограничьте количество результатов, возвращаемых запросом. Метод ограничения результатов будет зависеть от ваших требований — добавление LIMIT 1 к подзапросу будет работать, но вы можете захотеть сделать некоторую сортировку или использовать MIN/MAX, чтобы указать, какую строку вы получите.

Ryan P
14 март 2012, в 18:36

Поделиться

Проблема с вашим подзапросом:

SELECT ID, COUNT(ID) AS COUNTER FROM EIGENSCHAFTEN WHERE Kategorie = "BOUNCE" GROUP BY ID HAVING COUNTER = 1

вы пытаетесь сравнить его с ID, но возвращаете два столбца

James C
14 март 2012, в 18:47

Поделиться

UPDATE ADRESSEN
SET EMAIL = 0
WHERE ID = (SELECT ID
FROM EIGENSCHAFTEN WHERE Kategorie = "BOUNCE" 
GROUP BY ID
HAVING COUNT(*) = 1)

Teja
14 март 2012, в 19:38

Поделиться

WHERE ID IN (SELECT ID 
                FROM EIGENSCHAFTEN 
                WHERE Kategorie = "BOUNCE" 
                GROUP BY ID
                HAVING COUNT(*) = 1 )

DRapp
14 март 2012, в 18:44

Поделиться

Ещё вопросы

  • 1Итерация по параллельным спискам и преобразование текста с разделителями табуляции в одном списке в путь CSV в другом
  • 0Как воспроизведение метафайлов работает в GDI
  • 0Как стилизовать кнопку Тип ввода в HTML
  • 0Как загрузить и вставить несколько изображений в PHP?
  • 1Запись аудио в Android
  • 0HTML / CSS проблема с элементами, движущимися при разных разрешениях экрана
  • 0php get_headers ничего не возвращает, пока страница существует
  • 0Переполнение CloudZoom скрыто
  • 0Могу ли я моделировать другую модель нг?
  • 1событие шаблона для ожидания подписки до collection.find
  • 0MIN / MAX работает в JPA Spring Data с Amazon Aurora DB (запрос наибольшего числа групп)
  • 0Почему не работает ng-класс в ng-repeat?
  • 0Backbone.js — исключение ncaught: SyntaxError: Конструктор функции: не удалось скомпилировать функцию
  • 1FBconnect не работает в Android :(
  • 0Шаблонный кеш в ионных рамках
  • 0Создание проекта Symfony
  • 1Как читать Python колбу jsonify объект ответа
  • 1Поместите Google Maps Maker x Расстояние с y Подшипником?
  • 1Не удалось загрузить файл или сборку WPFToolkit
  • 0Функция поиска не работает
  • 0SQL альтернатива левому соединению
  • 0Добавление нескольких кнопок в корзину с помощью php
  • 0C ++ программа расчета стоимости ковровых покрытий
  • 0Пытаюсь выучить винапы. сделал первую программу, которая должна показать мне окно. CMD показывает но нет окна
  • 0Сложный выбор MYSQL-запроса из двух таблиц
  • 0JQuery добавить к ближайшему элементу, как я показываю
  • 1Перетаскивание в список
  • 0Используя PHP для отправки электронной почты, измените ОТ, чтобы это не имя моего сервера
  • 0yii2 две формы на одной странице
  • 1Python 3: бинарному дереву поиска не удалось установить узлы
  • 0addClass к переменной и добавить jQuery
  • 0Декодер, реализующий стек как связанную структуру
  • 0Как вернуть Symfony2.6 права доступа к файлам / папкам / права собственности по умолчанию?
  • 0выравнивание текста по вертикали с помощью CSS
  • 0Простой поиск в массиве C ++
  • 1SurfaceView отображает подачу камеры в сторону
  • 1Как заполнить значения Java-объекта в JSP
  • 1Отправка электронной почты в Java (работает локально) (Spring MVC)
  • 1Перезаписать файл Python при его использовании?
  • 0MySQL подбирает случайную запись, выбранную из определенного критерия
  • 1Spring Jdbc привязывает java.sql.timestamp к проблеме даты оракула
  • 0Jquery переключает только теги p под div нажал
  • 1Вызов метода с параметром Guid с использованием Reflection после использования CodeDomCompiler для компиляции сборки
  • 1Android — как улучшить HorizontalScrollView, который имеет много просмотров / изображений внутри
  • 1Ошибка внутреннего планировщика мобильных служб Azure .Net
  • 0JQuery: заполнить вторичные опции выбора, используя php на основе первичной выбранной опции
  • 0PHP абсолютный файл
  • 0При использовании DOM в цикле: Uncaught TypeError: Невозможно прочитать свойство ‘флажок’ с нулевой ошибкой
  • 0Нажмите импортировать изображение
  • 1Результаты графика Tensorflow отображаются случайными после восстановления

Понравилась статья? Поделить с друзьями:
  • Error 1241 21000 operand should contain 1 column s
  • Error 124 373 xerox
  • Error 123 the filename directory name or volume label syntax is incorrect
  • Error 123 getlasterror
  • Error 1227 mysql