2013-11-03 1 views
0

동일한 테이블을 사용하는 경우이 문제는 어떻습니까? 판매량이 가장 많은 책의 ID와 제목을 표시하십시오. 동점을 포함하십시오. 이 쿼리의 경우 판매 된 총 수량을 사용하십시오. 여기 서브 쿼리를 사용하면 판매량이 가장 많은 책의 ID와 제목을 표시 할 수 있습니다. 관계 포함

내가 무슨이지만, 잘못 :

select book_id, title 
From a_bkinfo.books 
Where book_id IN 
    (select book_id 
    From a_bkorders.order_details 
    where quantity IN 
     (Select SUM(quantity) 
     From a_bkorders.order_details 
    ) 
); 

테이블 : ---- 만들 ORDER_DETAILS ------

create table a_bkorders.order_details (
    order_id   integer   not null 
, order_line  integer   not null 
, book_id   integer   not null 
, quantity   integer   not null 
, order_price  numeric(6,2)  not null 
, constraint bk_orderline_pk   primary key (order_id, order_line) 
, constraint bk_orderline_order_fk foreign key (order_id) 
     references a_bkorders.order_headers(order_id) on delete cascade 
, constraint bk_orderline_book_fk foreign key (book_id) 
     references a_bkinfo.books(book_id) 
, constraint bk_quantity_ck   check (quantity > 0) 
, constraint bk_ordprice_ck   check (order_price >= 0) 
)engine = INNODB; 

---- 만들 book_topics ----

create table a_bkinfo.book_topics (
book_id   integer   not null 
, topic_id   varchar(5)  not null 
, constraint bk_book_topics_pk  primary key (book_id, topic_id) 
, constraint bk_books_topics_fk  foreign key(topic_id) 
     references a_bkinfo.topics(topic_id) 
, constraint bk_books_id_fk   foreign key(book_id) 
     references a_bkinfo.books(book_id) 
)engine = INNODB; 

--------- 만드는 책 ---------

0 그런
create table a_bkinfo.books (
book_id   integer   not null 
, title    varchar(75)  not null 
, publ_id   integer   null 
, year_publd  integer   not null 
, isbn    varchar(17)  null 
, page_count  integer   null 
, list_price  numeric(6,2)  null 
, constraint bk_books_pk    primary key (book_id) 
, constraint bk_books_publ_fk  foreign key(publ_id) 
     references a_bkinfo.publishers (publ_id) 
, constraint book_id_range   check (book_id > 1000) 
, constraint bk_page_count_ck  check (page_count >= 0) 
, constraint bk_price_ck    check (list_price >= 0)    
, constraint bk_books_year_ck  check (year_publd >= 1850) 
)engine = INNODB; 

답변

0

뭔가 :이 문제에 대한 몇 가지 솔루션입니다,하지만 난 하위 쿼리를 사용하는 대신 가입 및 연산자 "IN"을 피하기 사용하여 선호

select book_id, title 
From a_bkinfo.books 
Where book_id IN 
    (Select book_id, SUM(quantity) as max_q 
    From a_bkorders.order_details 
    group by book_id 
    order by max_q DESC 
    ); 
0

.

SELECT book_id, title 
    FROM books 
    JOIN ( SELECT book_id 
       FROM order_details 
      GROUP BY book_id 
      ORDER BY SUM(quantity) DESC 
      LIMIT 1) AS O 
    USING (book_id)