如何使用SQL中的其他表计算每一行?

时间:2016-03-26 13:22:35

标签: mysql sql

我有两个表:book table和author table。我需要为每个作者计算在书桌中登记了多少本书。怎么做?

3 个答案:

答案 0 :(得分:0)

sql语句中有一个group函数,名为count,可以添加group 例如

SELECT author_name
       Count(books.id)
FROM   author,
       book
WHERE  book.author_id = author_id 
GROUP BY AUTHOR

它会帮助你我猜

答案 1 :(得分:0)

我练习过您的问题是 SQLFIDDLE

以下是我使用的 SQL架构

create table book(  
  book_id int,
  author_name varchar(100),
  book_name varchar(100)
);
create table author(  
 author_id int,
 author_name varchar(100)
);
insert into author values(1, 'shovon');
insert into author values(11, 'arsho');
insert into author values(111, 'soda');
insert into author values(1111, 'nfs');
insert into book values(1, 'shovon', 'book shovon 1');
insert into book values(2, 'soda', 'book soda 1');
insert into book values(3, 'shovon', 'book shovon 2');
insert into book values(4, 'arsho', 'book arsho 1');
insert into book values(5, 'ar', 'book ar 1');

以下是我使用的查询:

select a.author_name, count(b.book_name) from 
(author as a 
  left join book as b on 
  a.author_name=b.author_name) 
group by a.author_name
order by count(b.book_name) desc;

SQLFIDDLE http://sqlfiddle.com/#!9/f11bc5/22

的网址

答案 2 :(得分:-1)

SELECT *,
       (SELECT Count(dbo.Book.ID)
        FROM   dbo.Book
        WHERE  dbo.Book.AuthorID = dbo.Author.ID) AS NumberOfBooks
FROM   dbo.Author 

您必须使用ID连接两个表,以便找出两个表的关系。