Subquery returns more than 1 row как исправить

I am executing this query:

SELECT
    voterfile_county.Name,
    voterfile_precienct.PREC_ID,
    voterfile_precienct.Name,
    COUNT((SELECT voterfile_voter.ID
FROM voterfile_voter
JOIN voterfile_household
WHERE voterfile_voter.House_ID = voterfile_household.ID
AND voterfile_household.Precnum = voterfile_precienct.PREC_ID)) AS Voters
FROM voterfile_precienct JOIN voterfile_county
WHERE voterfile_precienct.County_ID = voterfile_County.ID;

I am trying to make it return something like this:

County_Name   Prec_ID   Prec_Name   Voters(Count of # of voters in that precienct)

However, I am getting the error:

#1242 – Subquery returns more than 1 row.

I have tried placing the COUNT statement in the subquery but I get an invalid syntax error.

fragilewindows's user avatar

asked Apr 22, 2009 at 16:59

gsueagle2008's user avatar

gsueagle2008gsueagle2008

4,5539 gold badges36 silver badges46 bronze badges

2

If you get error:error no 1242 Subquery returns more than one row, try to put ANY before your subquery. Eg:

This query return error:

SELECT * FROM t1 WHERE column1 = (SELECT column1 FROM t2);

This is good query:

SELECT * FROM t1 WHERE column1 = ANY (SELECT column1 FROM t2);

2

You can try it without the subquery, with a simple group by:

SELECT voterfile_county.Name, 
  voterfile_precienct.PREC_ID, 
  voterfile_precienct.Name, 
  count(voterfile_voter.ID)
FROM voterfile_county
JOIN voterfile_precienct 
  ON voterfile_precienct.County_ID = voterfile_County.ID
JOIN voterfile_household 
  ON voterfile_household.Precnum = voterfile_precienct.PREC_ID
JOIN voterfile_voter 
  ON voterfile_voter.House_ID = voterfile_household.ID 
GROUP BY voterfile_county.Name, 
  voterfile_precienct.PREC_ID, 
  voterfile_precienct.Name

When you use GROUP BY, any column that you are not grouping on must have an aggregate clause (f.e. SUM or COUNT.) So in this case you have to group on county name, precienct.id and precient.name.

answered Apr 22, 2009 at 18:35

Andomar's user avatar

3

Try this

SELECT
voterfile_county.Name, voterfile_precienct.PREC_ID, 
voterfile_precienct.Name,
    (SELECT COUNT(voterfile_voter.ID) 
    FROM voterfile_voter JOIN voterfile_household
    WHERE voterfile_voter.House_ID = voterfile_household.ID
      AND voterfile_household.Precnum = voterfile_precienct.PREC_ID) as Voters
FROM voterfile_precienct JOIN voterfile_county 
ON voterfile_precienct.County_ID = voterfile_County.ID

answered Apr 22, 2009 at 17:03

Jhonny D. Cano -Leftware-'s user avatar

2

See the below example and modify your query accordingly.

select COUNT(ResultTPLAlias.id) from 
(select id from Table_name where .... ) ResultTPLAlias;

M Khalid Junaid's user avatar

answered May 18, 2011 at 7:55

Arunjith's user avatar

ArunjithArunjith

1312 silver badges10 bronze badges

Бывает так, что подзапрос одиночной строки возвращает более одной строки. В таком случае возникнет ошибка.

Для каждого магазина найдем одного сотрудника с должностью 'MANAGER'.

SELECT s.store_id,
       s.name,
       (SELECT e.employee_id
          FROM employee e
         WHERE e.store_id = s.store_id
           AND e.rank_id = 'MANAGER'
       ) AS employee_id
  FROM store s
 ORDER BY s.store_id
error: more than one row returned by a subquery used as an expression

Посмотрим, что там с данными не так?

SELECT e.store_id,
       e.rank_id,
       e.last_name || ' ' || e.first_name AS full_name 
  FROM employee e
 WHERE e.rank_id = 'MANAGER'
 ORDER BY e.store_id, e.last_name, e.first_name

В магазине 201 два менеджера, а в магазине 600 – три.

В такой ситуации есть два варианта развития событий. Мы можем решать неправильную задачу. Если в магазине может быть несколько менеджеров, то мы должны работать с массивом менеджеров. В таком случае может быть приемлемым получить одного из них, например, первого по алфавиту.

Возможно, менеджер в магазине должен быть только один. Просто кто-то не создал уникальный ключ, и пользователи создали несколько менеджеров в магазине. В таком случае, мы написали правильный запрос и необходимо избавляться от неправильных данных и дорабатывать структуру данных.

В любом случае, необходимо гарантировать, что в результате подзапроса будет возвращено не более одной строки. Для этого необходимо одно из:

  • должен быть уникальный ключ, гарантирующий, что в результате подзапроса будет не более одной строки;
  • использовать агрегатную функцию;
  • использовать LIMIT 1 для ограничения количества строк.

Воспользуемся LIMIT 1:

SELECT s.store_id,
       s.name,
       (SELECT e.employee_id
          FROM employee e
         WHERE e.store_id = s.store_id
           AND e.rank_id = 'MANAGER'
         ORDER BY e.last_name,
                  e.first_name,
                  e.middle_name
         LIMIT 1
       ) AS employee_id
  FROM store s
 ORDER BY s.store_id

P.S. Если нам нужен список ФИО, то можно воспользоваться string_agg:

SELECT s.store_id,
       s.name,
       (SELECT string_agg (
                  e.last_name || ' ' || e.first_name, '; '
                  ORDER BY e.last_name,
                           e.first_name
               )
          FROM employee e
         WHERE e.store_id = s.store_id
           AND e.rank_id = 'MANAGER'
       ) AS employees
  FROM store s
 ORDER BY s.store_id

Таких функций в PostgreSQL довольно много, и они заслуживают отдельной темы.

Здравствуйте, не понимаю какое добавить еще условие, чтобы решить

DELIMITER //
CREATE TRIGGER Buget_Trigger
    AFTER INSERT
    ON Buget5
    FOR EACH ROW BEGIN
    if((select MaxCount from Buget5 where  (select max(dateee) where dateee<(now())) )<(select Buget from Buget5 where  (select max(dateee) where dateee<(now())))) then
      update Insects set Count=Count+20 where(select max(datee) where datee<(now()));
      update Mammals set Count=Count+20 where(select max(datee) where datee<(now()));
      update ColdBloodedness set Count=Count+20 where(select max(datee) where datee<(now()));
    end if;
    END //

insert into Mammals(mammals_id, id, typee, count, datee) VALUES (1,null,'',7,'2019-12-13');
insert into ColdBloodedness(ColdBloodedness_Id, id, typee,datee, count) VALUES (1,null,'','2019-12-13',10);
insert into Insects(insects_id, id, typee, count,datee) VALUES (1,null,'',5, '2019-12-13');
insert into Buget5(buget_id, id, buget, maxcount, dateee) VALUES (1, null,600, 200,'2019-12-13');
select * from Insects;
select * from ColdBloodedness;
select * from Mammals;

Но если сделаю второй раз, то ничего не сработает и будет ошибка 1242

insert into Buget5(buget_id, id, buget, maxcount, dateee) VALUES (2, null,600, 200,'2019-12-13');
select * from Insects;
select * from ColdBloodedness;
select * from Mammals;

If you’re working with SQL queries, you may have come across the error message “More than one row returned by a subquery used as an expression.” This error occurs when a subquery returns multiple rows, but the main query is expecting only one result. In this guide, we’ll explain what causes this error and provide step-by-step instructions on how to fix it.

What Causes the ‘More Than One Row Returned by a Subquery Used as an Expression’ Error?

This error occurs when a subquery returns more than one row, but the main query is expecting only one result. The main query may be using a subquery as a condition, such as in a WHERE or HAVING clause, or as a value in a SELECT statement.

For example, consider the following query:

SELECT customer_name, (SELECT SUM(order_total) FROM orders WHERE customer_id = customers.id) as total_orders
FROM customers

This query is trying to retrieve the customer name and the total order amount for each customer. However, if there are multiple orders for a customer, the subquery in the SELECT statement will return multiple rows, causing the “More than one row returned by a subquery used as an expression” error.

To fix this error, you need to ensure that the subquery returns only one row. There are several ways to do this, depending on the context of the query.

1. Use an Aggregate Function

One way to ensure that the subquery returns only one row is to use an aggregate function, such as SUM, AVG, or COUNT. This will combine the multiple rows returned by the subquery into a single value.

For example, you can rewrite the previous query as follows:

SELECT customer_name, (SELECT SUM(order_total) FROM orders WHERE customer_id = customers.id GROUP BY customer_id) as total_orders
FROM customers

By adding a GROUP BY clause to the subquery, we’re telling SQL to group the orders by customer ID and then calculate the total order amount for each group using the SUM function. This will ensure that the subquery returns only one row per customer.

2. Use a Subquery as a Table

Another way to ensure that the subquery returns only one row is to use it as a table and join it with the main query. This will allow you to filter or group the subquery results based on the criteria in the main query.

For example, consider the following query:

SELECT customer_name, total_orders
FROM customers
JOIN (
    SELECT customer_id, SUM(order_total) as total_orders
    FROM orders
    GROUP BY customer_id
) as order_totals
ON customers.id = order_totals.customer_id

In this query, we’re joining the customers table with a subquery that calculates the total order amount for each customer. By using the subquery as a table and joining it with the main query, we can ensure that the subquery returns only one row per customer.

3. Use a LIMIT Clause

If you’re certain that the subquery should return only one row, you can use a LIMIT clause to ensure that it does. This will limit the number of rows returned by the subquery to one.

For example, consider the following query:

SELECT customer_name, (SELECT order_total FROM orders WHERE customer_id = customers.id LIMIT 1) as total_order
FROM customers

In this query, we’re using a subquery to retrieve the total order amount for each customer. However, we’re adding a LIMIT 1 clause to the subquery to ensure that it returns only one row. This will prevent the “More than one row returned by a subquery used as an expression” error.

FAQ

Q1. What is a subquery in SQL?

A subquery in SQL is a query that is embedded within another query. It is used to retrieve data that will be used as a condition or value in the main query.

Q2. What causes the “More than one row returned by a subquery used as an expression” error?

This error occurs when a subquery returns more than one row, but the main query is expecting only one result. This can happen when the subquery is used as a condition, such as in a WHERE or HAVING clause, or as a value in a SELECT statement.

Q3. How do I fix the “More than one row returned by a subquery used as an expression” error?

To fix this error, you need to ensure that the subquery returns only one row. You can do this by using an aggregate function, using a subquery as a table, or using a LIMIT clause.

Q4. What is an aggregate function in SQL?

An aggregate function in SQL is a function that performs a calculation on a set of values and returns a single value. Examples of aggregate functions include SUM, AVG, COUNT, MIN, and MAX.

Q5. Can I use a subquery in a JOIN statement?

Yes, you can use a subquery in a JOIN statement. This allows you to join two or more tables based on a condition that is calculated using the subquery.

There’re two error patterns related to ORA-01427 described in this post:

  1. SELECT with Equal Operator
  2. Job Failed by Trigger.

I will talk about them respectively in the following sections. In which, the first error pattern is very common and easy to solve. But the second one is not so obvious, you need more patience to solve it.

A. ORA-01427 in SELECT with Equal Operator

If SQL engine expects your subquery to return a single row, it may throw ORA-01427 when the subquery returns more than one row unexpectedly. For example:

SQL> select * from employees where department_id = (select department_id from departments where location_id = 1700);
select * from employees where department_id = (select department_id from departments where location_id = 1700)
                                               *
ERROR at line 1:
ORA-01427: single-row subquery returns more than one row

This is because the subquery in the SELECT statement returned more than one row for the predicate department_id, which does not comply with a singular value limited operator, the equal =. Consequently, the statement fails to continue and then throw ORA-01427 to notify developers.

Solutions

It’s just like that we wanted strictly only one item, but eventually it returned more than we expected.

Equal Sign Wants Only One. But Get More Eventually!

Equal Sign Wants Only One. But Get More Eventually!

1. Using IN Operator

Then what operator is used to prevent ORA-01427 in SELECT statement? In practice, SELECT should use IN operator instead of = (equal operator) in order to accommodate more than one row returned by the subquery.

SQL> select * from employees where department_id in (select department_id from departments where location_id = 1700);

A similar exception that relates to returned number mismatch is ORA-00913: too many values. But they have different error patterns.

More comparison conditions like ANY, SOME or ALL should also be helpful to accept more than one row in your statements so as to avoid ORA-01427 in subquery statement.

2. Using = (Equal) Operator

If you really want to use an equal operator to confine the scope of returned rows as one, you have to limit the number of rows returned of queries to only one row. That’s how we workaround it.

SQL> select * from employees where department_id = (select * from (select department_id from departments where location_id = 1700) where rownum = 1);

An order by clause is more appropriate in the above subquery so as to be close to your expectation.

select * from employees where department_id = (select * from (select department_id from departments where location_id = 1700 order by manager_id) where rownum = 1);

3. Do Not Use DISTINCT with Equal Operator

Adding one distinct keyword before column list cannot prevent ORA-01427, because the number of rows returned by the subquery is still unpredictable.

SQL> select * from employees where department_id = (select distinct department_id from departments where location_id = 1700);
select * from employees where department_id = (select distinct department_id from departments where location_id = 1700)
                                               *
ERROR at line 1:
ORA-01427: single-row subquery returns more than one row

No surprises, we saw ORA-01427 in SELECT statement once again.

B. ORA-01427 in Job Failed by Trigger

ORA-12012 and ORA-01427

ORA-12012 and ORA-01427

Same error ORA-01427 could accompany ORA-12012 in the alert log when one scheduled job failed to complete successfully.

ORA-12012: error on auto execute of job 10
ORA-01427: single-row subquery returns more than one row
ORA-06512: at line 21

Trigger Caused ORA-01427

According to this error pattern in the above, we saw ORA-01427 in a failed job with ORA-12012. We’d better check some triggers, especially logon and logoff ones to see if there’s any chances to block the job process accidentally. Noticeably, which is Job No. 10 in this case.

You should check the content of the job in the first place to see if there’re any chances to throw ORA-01427. Perhaps you should disable each trigger at a time in order to isolate and identify the cause. Or just turn them off temporarily.

Further reading: How to Kill Session in Logon Trigger

C. MySQL Subquery Returns More Than 1 Row

The same error pattern occurs in MySQL, incorrect number of rows from subquery will result ERROR 1241, let’s see its content:

ERROR 1242 (ER_SUBSELECT_NO_1_ROW)
SQLSTATE = 21000
Message = “Subquery returns more than 1 row”

This error is caused by the subquery that must return at most one row but returns multiple rows eventually.

mysql> select * from items where id = (select item_id from orders);

If the subquery returns just one row, the above query will work without errors. If it returns more than one row, we will see error 1242.

The solution is the same as we mentioned in the above sections. Beside IN operator, we can also use ANY, one of comparison conditions to fix the query, for example:

mysql> select * from items where id = any (select item_id from orders);

This is how comparison conditions work for MySQL.

Добавить комментарий