计数和子选择

时间:2012-11-30 00:53:53

标签: mysql sql

我有一个选项,带来标题,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 个答案:

答案 0 :(得分: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需要合格......但我不知道哪个表来自哪个,所以你可以自己添加。