2012-11-30 72 views
1

我有一個選擇,可以調出標題,bookcopiesid和名稱。計數和子選擇

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); 

工作。

我想顯示的圖書數量爲每名

+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子句中的列(就像您在WHERE子句中所做的那樣)。

另外,return_date需要限定...但我不知道哪個表來自哪裏,所以你可以在自己的地方添加。