Mysql添加join子查询来计算

时间:2015-10-31 17:25:37

标签: mysql join count

我有两张桌子贷款和书。

通过这个查询,我通过计算Book_ID来计算贷款中大部分借出的书籍:

select Book_ID, count(Book_ID) as Count
from Loan
group by Book_ID
order by Count desc;

现在我想从Book表中添加Book title。我在贷款表中将Book_ID作为外键。我不太确定如何将这个查询放在一起。

这是我尝试但没有结果:

select Book_ID, count(Book_ID) as Count, Book.Title
from Loan, Book
where Loan.Book_ID = Book.Book_ID
group by Book_ID
order by Count desc;

1 个答案:

答案 0 :(得分:1)

由于您已加入另一个表,因此您拥有不明确的列名,请尝试为它们添加别名:

select Book.Book_ID, count(Book.Book_ID) as Count, Book.Title
from Loan, Book
where Loan.Book_ID = Book.Book_ID
group by Book.Book_ID
order by Count desc;