2012-11-30 39 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需要限定...但我不知道哪个表来自哪里,所以你可以在自己的地方添加。