2012-11-30 3 views
1

나는 select, title, bookcopiesid, 그리고 name을 가지고있다.카운트와 서브 선택

select 
    books.title, borrow.bookcopiesid, users.name, usersid,library_locations.name, checkout_date, return_date, due_date 
FROM 
    books, borrow,users, library_locations, userlib 
WHERE 
    library_locations.id = userlib.libid 
AND 
    userlib.userid = users.id 
AND 
    borrow.bookcopiesid = books.bookid 
AND 
    borrow.usersid = users.id and return_date is not null ; 

어떻게 작동하는

SELECT title, COUNT(*) as count 
FROM (
    SELECT books.title, borrow.bookcopiesid, users.name, usersid,library_locations.name, checkout_date, return_date, due_date 
    FROM books, borrow,users, library_locations, userlib 
    WHERE library_locations.id = userlib.libid and userlib.userid = users.id and borrow.bookcopiesid = books.bookid and borrow.usersid = users.id and return_date is not null) 
GROUP BY title 
ORDER BY count DESC); 

같은 것을 얻을 것입니다.

i는 각각의 이름

+1

테이블 구조와 게시하려는 출력 샘플을 게시하면 도움이됩니다. – bobwienholt

답변

1

나는 이것이 당신이 찾고있는 무슨 생각을 위해 타이틀의 수를 표시하려고?

SELECT 
    books.title, 
    COUNT(*) as count 
FROM 
    books, 
    borrow, 
    users, 
    library_locations, 
    userlib 
WHERE 
    library_locations.id = userlib.libid 
    AND userlib.userid = users.id 
    AND borrow.bookcopiesid = books.bookid 
    AND borrow.usersid = users.id 
    AND return_date is not null 
GROUP BY books.title 
ORDER BY COUNT(*) DESC; 

하위 쿼리가 필요하지 않습니다. 너 절에서했던 것처럼 SELECTGROUP BY 절의 열을 한정하면됩니다.

또한 return_date이 자격이 필요합니다 ...하지만 나는 어떤 테이블에서 왔는지 알지 못하므로 직접 추가 할 수 있습니다.

관련 문제