I got an error: #1242 — Subquery returns more than 1 row when i run this sql.
CREATE VIEW test
AS
SELECT cc_name,
COUNT() AS total,
(SELECT COUNT(*)
FROM bed
WHERE respatient_id > 0
GROUP BY cc_name) AS occupied_beds,
(SELECT COUNT(*)
FROM bed
WHERE respatient_id IS NULL
GROUP BY cc_name) AS free_beds
FROM bed
GROUP BY cc_name;
OMG Ponies
326k82 gold badges523 silver badges502 bronze badges
asked Oct 23, 2011 at 16:00
6
The problem is that your subselects are returning more than one value — IE:
SELECT ...
(SELECT COUNT(*)
FROM bed
WHERE respatient_id IS NULL
GROUP BY cc_name) AS free_beds,
...
…will return a row for each cc_name
, but SQL doesn’t support compacting the resultset for the subselect — hence the error.
Don’t need the subselects, this can be done using a single pass over the table using:
SELECT b.cc_name,
COUNT(*) AS total,
SUM(CASE
WHEN b.respatient_id > 0 THEN 1
ELSE 0
END) AS occupied_beds,
SUM(CASE
WHEN b.respatient_id IS NULL THEN 1
ELSE 0
END) AS free_beds
FROM bed b
GROUP BY b.cc_name
answered Oct 23, 2011 at 16:05
OMG PoniesOMG Ponies
326k82 gold badges523 silver badges502 bronze badges
8
This is because your subqueries (the SELECT
bits that are inside parentheses) are returning multiple rows for each outer row. The problem is with the GROUP BY
; if you want to use subqueries for this, then you need to correlate them to the outer query, by specifying that they refer to the same cc_name
as the outer query:
CREATE VIEW test
AS
SELECT cc_name,
COUNT() AS total,
(SELECT COUNT()
FROM bed
WHERE cc_name = bed_outer.cc_name
AND respatient_id > 0) AS occupied_beds,
(SELECT COUNT(*)
FROM bed
WHERE cc_name = bed_outer.cc_name
WHERE respatient_id IS NULL) AS free_beds
FROM bed AS bed_outer
GROUP BY cc_name;
(See http://en.wikipedia.org/wiki/Correlated_subquery for information about correlated subqueries.)
But, as OMG Ponies and a1ex07 say, you don’t actually need to use subqueries for this if you don’t want to.
answered Oct 23, 2011 at 16:11
ruakhruakh
176k26 gold badges273 silver badges307 bronze badges
2
Your subqueries return more than 1 row. I think you you need something like :
SELECT COUNT(*) AS total,
COUNT(CASE WHEN respatient_id > 0 THEN 1 END) AS occupied_beds,
COUNT(CASE WHEN respatient_id IS NULL THEN 1 END) AS free_beds
FROM bed
GROUP BY cc_name
You can also try to use WITH ROLLUP
+ pivoting (mostly for learning purposes, it’s a much longer query ) :
SELECT cc_name,
MAX(CASE
WHEN num_1 = 1 THEN tot_num END) AS free_beds,
MAX(CASE
WHEN num_1 = 2 THEN tot_num END) AS occupied_beds,
MAX(CASE
WHEN num_1 = IS NULL THEN tot_num END) AS total
FROM
(SELECT cc_name, CASE
WHEN respatient_id > 0 THEN 1
WHEN respatient_id IS NULL THEN 2
ELSE 3 END as num_1,
COUNT(*) as tot_num
FROM bed
WHERE
CASE
WHEN respatient_id > 0 THEN 1
WHEN respatient_id IS NULL THEN 2
ELSE 3 END != 3
GROUP BY cc_name,
num_1 WITH ROLLUP)A
GROUP BY cc_name
answered Oct 23, 2011 at 16:06
a1ex07a1ex07
36.9k12 gold badges90 silver badges103 bronze badges
SELECT COUNT()
FROM bed
WHERE respatient_id > 0
GROUP BY cc_name
You need to remove the group-by in the sub query, so possibly something like
SELECT COUNT(*)
FROM bed
WHERE respatient_id > 0
or possibly — depending on what your application logic is….
SELECT COUNT(*) from (
select count(*),cc_name FROM bed
WHERE respatient_id > 0
GROUP BY cc_name) filterview
answered Oct 23, 2011 at 16:02
SorenSoren
14.4k4 gold badges41 silver badges67 bronze badges
Здравствуйте, не понимаю какое добавить еще условие, чтобы решить
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;
Getting error : #1242 - Subquery returns more than 1 row
while executing this
SELECT `Index` , `FundName` ,Count(*),
(SELECT COALESCE(sum(b.PricePerWeek),0)
FROM tbl_FundSubscriptions
WHERE DATE_SUB(CURDATE(),INTERVAL 7 DAY) <= SubscribeDt
GROUP BY FundIDSend)
FROM tbl_FundSubscriptions b, tbl_FundStatic a
WHERE a.FundID = b.FundIDSend
AND FundIDSend IN
(SELECT FundID
FROM tbl_FundStatic
WHERE UserID = '14')
GROUP BY a.FundName,a.Index
What could be wrong?
Thanks
OMG Ponies
326k82 gold badges523 silver badges502 bronze badges
asked Feb 14, 2011 at 13:41
Parth BhattParth Bhatt
19.4k28 gold badges133 silver badges216 bronze badges
4
Is this the query you’re looking for? Not knowing your table structure, we’ll never know, but this does what your query appears to have been indented to do. (Does that make any sense at all?)
SELECT `Index`, `FundName`, COUNT(*),
(SELECT SUM(`PricePerWeek`)
FROM `tbl_FundSubscriptions`
WHERE DATE_SUB(CURDATE(),INTERVAL 7 DAY) <= `SubscribeDt`
AND `FundIDSend` = `tbl_FundStatic`.`FundID`)
FROM `tbl_FundStatic`
WHERE `UserID` = '14'
answered Feb 14, 2011 at 14:05
Your subquery is returning more then 1 row.
Either you LIMIT
the subquery to one row or you LEFT JOIN
it with the other table.
answered Feb 14, 2011 at 13:44
BobbyBobby
11.4k5 gold badges44 silver badges69 bronze badges
2
If you are working with MySQL, you might come across a problem where a subquery returns more than one row. This can happen when you use a subquery in a WHERE or HAVING clause, and that subquery returns multiple rows. In this guide, we will explain what causes this problem and how you can fix it with code examples.
Understanding the Problem
When you use a subquery in a WHERE or HAVING clause, MySQL expects the subquery to return only one row. However, if your subquery returns multiple rows, MySQL will throw an error. This error message will look something like this:
ERROR 1242 (21000): Subquery returns more than 1 row
This problem can be caused by a variety of factors, such as using an incorrect JOIN condition or not using a LIMIT clause in your subquery. Whatever the cause, the solution is usually to modify your SQL query to return only one row in the subquery.
Fixing the Problem
Here are some examples of how you can fix the problem of a MySQL subquery returning more than one row:
Example 1: Use the IN Operator
One way to fix the problem is to use the IN operator instead of the = operator. For example, instead of writing:
SELECT *
FROM table1
WHERE column1 = (SELECT column1 FROM table2 WHERE condition);
You can write:
SELECT *
FROM table1
WHERE column1 IN (SELECT column1 FROM table2 WHERE condition);
This will return all rows from table1 where column1 matches any of the values returned by the subquery.
Example 2: Use the EXISTS Operator
Another way to fix the problem is to use the EXISTS operator. For example, instead of writing:
SELECT *
FROM table1
WHERE column1 = (SELECT column1 FROM table2 WHERE condition);
You can write:
SELECT *
FROM table1
WHERE EXISTS (SELECT column1 FROM table2 WHERE condition AND table1.column1 = table2.column1);
This will return all rows from table1 where there exists at least one row in table2 that matches the condition.
Example 3: Use the LIMIT Clause
If you know that your subquery should only return one row, you can use the LIMIT clause to limit the number of rows returned. For example:
SELECT *
FROM table1
WHERE column1 = (SELECT column1 FROM table2 WHERE condition LIMIT 1);
This will return all rows from table1 where column1 matches the value returned by the subquery, but will only return the first row of the subquery.
Conclusion
If you are getting an error message saying that your MySQL subquery returns more than one row, don’t panic! This is a common problem that can be easily fixed. By using the IN and EXISTS operators or the LIMIT clause, you can modify your SQL query to return only one row in the subquery. We hope this guide has been helpful in solving your MySQL subquery problem.
у меня есть две таблицы в БД со следующей структурой:
Таблица 1: 3 строки — category_id, product_id и position
таблица 2: 3 строки — category_id, product_id и position
я пытаюсь установить положение таблицы 1 в положение таблицы 2, где категория и идентификатор продукта совпадают с таблицами.
ниже SQL, я пытался сделать это, но возвращает ошибку MySQL 1242 — подзапрос возвращает более 1 строки
UPDATE table1
SET position = (
SELECT position
FROM table2
WHERE table1.product_id = table2.product_id AND table1.category_id = table2.category_id
)
1
Решение
Решение очень простое и может быть сделано в два простых шага. Первый шаг — это предварительный просмотр того, что будет изменено, чтобы избежать уничтожения данных. Это можно пропустить, если вы уверены в своем WHERE
пункт.
Шаг 1: предварительный просмотр изменений
Объедините таблицы, используя поля, которые вы хотите сопоставить, выберите все для визуальной проверки соответствия.
SELECT t1.*, t2.*
FROM table1 t1
INNER JOIN table2 t2
ON t1.category_id = t2.category_id
AND t1.product_id = t2.product_id
Вы также можете добавить WHERE
предложение, если только некоторые строки должны быть изменены.
Шаг 2: сделать актуальное обновление
Заменить SELECT
пункт и FROM
ключевое слово с UPDATE
, добавить SET
пункт, где это принадлежит. Держать WHERE
пункт:
UPDATE table1 t1
INNER JOIN table2 t2
ON t1.category_id = t2.category_id
AND t1.product_id = t2.product_id
SET t1.position = t2.position
Это все.
Технические соображения
Индексы столбцов, используемых на JOIN
предложение в обеих таблицах является обязательным, если в таблицах более нескольких сотен строк. Если запрос не имеет WHERE
условия, то MySQL будет использовать индексы только для самой большой таблицы. Индексы полей, используемых на WHERE
условие ускорит запрос. Prepend EXPLAIN
к SELECT
запрос, чтобы проверить план выполнения и решить, какие индексы вам нужны.
Можете добавить SORT BY
а также LIMIT
для дальнейшего сокращения набора измененных строк, используя критерии, которые не могут быть достигнуты с помощью WHERE
(например, только самые последние / самые старые 100 строк и т. д.). Поместите их на SELECT
сначала запрос, чтобы проверить результат, а затем изменить SELECT
в UPDATE
как описано.
Конечно, индексы на столбцах, используемых на SORT BY
пункт является обязательным.
1
Другие решения
Вы можете запустить этот запрос, чтобы увидеть, что происходит:
SELECT product_id, category_id, count(*), min(position), max(position)
FROM table2
GROUP BY product_id, category_id
HAVING COUNT(*) > 1;
Это даст вам список product_id
, category_id
пары, которые появляются несколько раз в table2
, Тогда вы можете решить, что делать. Вы хотите произвольное значение position
? Является ли значение position
всегда одно и то же? Вам нужно починить стол?
Достаточно легко решить конкретную проблему с помощью limit 1
или функция агрегации. Тем не менее, вам может понадобиться исправить данные в таблице. Исправление выглядит так:
UPDATE table1 t1
SET t1.position = (SELECT t2.position
FROM table2 t2
WHERE t2.product_id = t1.product_id AND t2.category_id = t1.category_id
LIMIT 1
);
0