I am writing a nested MySQL quer开发者_如何转开发y where a subquery returns more than one row and hence the query can not be executed.
Can anyone suggest me a solution for this problem?
Thanks in advance.
An error about a subquery returning more than one value says to me that you're attempting a straight value comparison, like this:
WHERE col = (SELECT col2 FROM TABLE_2)
The solution depends on the data coming from the subquery - do you want the query to use all the values being returned? If yes, then change the equals sign for an IN:
WHERE col IN (SELECT col2 FROM TABLE_2)
Otherwise, you need to correct the subquery so it only ever returns one value. The MAX or MIN aggregate functions are a possibliity - they'll return the highest or lowest value. It could just be a matter of correlating the subquery:
FROM TABLE_1 t1
WHERE t1.col = (SELECT MAX(t2.col2)
FROM TABLE_2 t2
WHERE t2.fk_col = t1.id) -- correlated example
As Tabhaza points out, a subquery generally doesn't return more than one column (though some databases support tuple matching), in which case you need to define a derived table/inline view and join to it.
Would've been nice to have more information on the issue you're having...
Try joining to a derived table rather than doing a subquery; it will allow you to return multiple fields:
SELECT a.Field1, a.Field2, b.Field3, b.Field4
FROM table1 a INNER JOIN
(SELECT c.Field3, c.Field4, c.Key FROM table2 as c) as b ON a.Key = b.Key
WHERE ...
this sounds like a logic problem, not a syntax problem.
why is the subquery returning more than one row?
why do you have that in a place that requires only one row?
you need to restructure something to fit these two things together. without any indication of your system, your query, or your intent, it is very hard to help further.
If the database says you are returning more than one row, you should listen to what it says and change your query so that it only returns one row.
This is a problem in your logic.
Change the query so that it only returns one row.
Think about why the query is returning more than one row, and determine how to get the query to return just the single row you need from that result.
Use a LIMIT clause on the subquery so it always returns a maximum of 1 row
You could add a LIMIT 1
to the subquery so the top query only considers the first result. You can also sort the results from the subquery before doing the LIMIT, to return the result with the highest/lowest X. But make sure that that's actually what you want to happen, as the multi-row subquery is often a symptom of an underlying problem.
精彩评论