简体   繁体   English

子查询从mysql返回多个行错误结果

[英]Subquery returns more than one row error result from mysql

I have a question, I am trying to go through a data base and display all the books by an author based on a search where I use an author name to get isbn and then find all the details of that isbn...well if the author wrote one book it is displaying one row but when the author wrote more than one book it is giving me an error...what am I doing wrong can you please help...Here is my code. 我有一个问题,我正在尝试通过数据库并显示作者基于搜索的所有书籍,我使用作者名称获取isbn,然后找到该isbn的所有细节......如果作者写了一本书,它显示了一行,但当作者写了不止一本书时,它给了我一个错误......我做错了什么,请你帮忙......这是我的代码。

SELECT* FROM books WHERE isbn=(SELECT isbn FROM books_authors 
  WHERE author_id IN 
 (SELECT author_id FROM authors WHERE first_name ="J.K."))

Change to: 改成:

SELECT* FROM books WHERE isbn in (SELECT isbn FROM books_authors 
  WHERE author_id IN 
 (SELECT author_id FROM authors WHERE first_name ="J.K."))

You can't have isbn=(subquery) if the subquery returns multiple results. 如果子查询返回多个结果,则不能使用isbn=(subquery)

Try: 尝试:

SELECT * FROM books 
 WHERE isbn IN (SELECT isbn FROM books_authors 
                  WHERE author_id IN (SELECT author_id 
                                        FROM authors 
                                       WHERE first_name ="J.K."
                                     )
               ) ;

Note that the outmost select should also have WHERE isbn IN... . 请注意,最外面的选择也应该有WHERE isbn IN...

You can do this query avoinding subselect and in clause (using join) 您可以执行此查询以避免subselect和in子句(使用join)

SELECT * FROM books 
INNER JOIN books_authors on books_authors.isbn = books.isbn
INNER JOIN authors on authors.author_id =  books_authors.author_id
WHERE authors.first_name = J.K.";

Anyway your error happen because you are using = instead of in for the first part of your quert SELECT* FROM books WHERE isbn=(SELECT isbn FROM ... i fyou want use your query you should use SELECT* FROM books WHERE isbn in (SELECT isbn FROM ..... 无论如何你的错误发生是因为你正在使用=而不是在你的quert的第一部分SELECT* FROM books WHERE isbn=(SELECT isbn FROM ...我想你使用你的查询你应该使用SELECT* FROM books WHERE isbn in (SELECT isbn FROM .....

NEVER use nested sub-queries when you can get the desired result using a join, particularly on MySQL: 当您可以使用连接获得所需的结果时,切勿使用嵌套的子查询,尤其是在MySQL上:

SELECT b.* 
FROM books b
INNER JOIN books_authors ba
   ON b.isbn=ba.isbn
INNER JOIN authors a
   ON ba.author_id=a.author_id
WHERE a.first_name ="J.K.";

While you can use 'IN' inplace of '=' in your original query, the optimizer won't be able to do much with the query, it is inflexible and difficult to maintain. 虽然您可以在原始查询中使用'IN'代替'=',但优化程序将无法对查询执行太多操作,但它不灵活且难以维护。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM