#1242 - Subquery returns more than 1 row
This error occurs when a subquery being used in a query returns more than one row. In SQL, a subquery is a query that is nested inside another query.
For example, let's say you have two tables: customers and orders. You want to find all customers who have made more than one order. You can write the following query:
SELECT * FROM customers WHERE customer_id IN (SELECT customer_id FROM orders GROUP BY customer_id HAVING COUNT(*) > 1);
In this query, the subquery is "SELECT customer_id FROM orders GROUP BY customer_id HAVING COUNT(*) > 1". This subquery returns the customer_id of all customers who have made more than one order. However, if two or more customers have made more than one order, this subquery will return more than one row, causing the error "Subquery returns more than 1 row".
To fix this error, you can modify the subquery to return only one row. One way to do this is to use an aggregate function like MAX() or MIN() to select one value from the subquery's result set. For example:
SELECT * FROM customers WHERE customer_id IN (SELECT MAX(customer_id) FROM orders GROUP BY customer_id HAVING COUNT(*) > 1);
In this modified query, the subquery returns only one customer_id for each group of customers who have made more than one order, by using the MAX() function. This ensures that the subquery returns only one row for each customer, and the error is avoided.
原文地址: https://www.cveoy.top/t/topic/wIj 著作权归作者所有。请勿转载和采集!