【问题标题】:How to do this search in SQL如何在 SQL 中进行此搜索
【发布时间】:2020-05-03 03:38:01
【问题描述】:

我的任务是创建一个陈述来回答这个问题:

列出每位作者(按姓氏和名字)以及作者撰写的书籍数量。

数据库有三个将要使用的表

带有 isbn(主要)、标题、类型、pub_id、价格、预付款、ytd_sales、pub_date 的书表

bookauthor 表(介于书籍和作者之间),author_id(primary),isbn,author_order,royalshare

author_id(primary)、ssn、姓氏、名字、电话、地址、城市、州、邮编的作者表

select author.lastname, author.firstname, bookauthor.count(author_id)
from author a
join bookauthor ba on ba.author_id = a.author_id
group by lastname

这就是我得到的,但它不起作用,无论出于何种原因,我都很难理解这些带有 join 和 in 的 SQL 语句以及这些类型的语句。如果有人能帮助更多地解释这个过程,那将不胜感激。

【问题讨论】:

  • MySQL 还是 SQL Server?
  • 两位作者同名并不代表他们是同一个人。这就是为什么你有一个 author_id!
  • @Strawberry 好点。我已经更新了我的答案以考虑到这一点。

标签: mysql sql sql-server


【解决方案1】:

您有一些问题。从查询开始:

  1. 当您定义表别名(aauthor 的别名)时,您必须在您专门引用 author 表的任何地方使用该别名,因此在您的 SELECT你应该说SELECT a.lastname, a.firstname
  2. 当你想COUNT 某事时,表名在COUNT 中,你必须再次使用你定义的表别名:COUNT(ba.author_id)
  3. 您可以为计数使用列别名,以便更容易引用,例如COUNT(ba.author_id) AS num_books
  4. 您应该使用LEFT JOIN,这样您就可以列出没有写过书的作者(如果有的话)
  5. 为了严格遵守,您应该GROUP BY所有非聚合列,所以这需要GROUP BY a.lastname, a.firstname
  6. 正如@Strawberry 所指出的,你真的应该按author_id 分组,因为可能有两个作者有相同的名字。由于author_id 是主键,因此在 MySQL 中只按该字段分组是可以的,但 SQL Server 要求您仍按 lastnamefirstname 分组。

总的来说,您的查询应该是:

SELECT a.lastname, a.firstname, COUNT(ba.author_id) AS num_books
FROM author a
LEFT JOIN bookauthor ba ON ba.author_id = a.author_id
GROUP BY a.author_id, a.lastname, a.firstname

【讨论】:

    【解决方案2】:

    一旦你给一个表加上了别名,你需要在以后引用那个表时使用这个别名:

    select 
        a.lastname, 
        a.firstname, 
        TotalBooksForAuthor = count(a.author_id)
    from 
        author a
        join bookauthor ba on ba.author_id = a.author_id
    group by
        a.author_id,
        a.lastname,
        a.firstname
    

    【讨论】:

      【解决方案3】:

      您在group by 中缺少firstname。此外,您使用count 的方式也不正确。试试下面的。

      select 
          lastname, 
          firstname, 
          count(author_id) as total_books
      from author a
      join bookauthor ba 
      on ba.author_id = a.author_id
      group by 
          lastname,
          firstname
      

      【讨论】:

        【解决方案4】:

        您应该在您的 group by 中包含 select 中的所有列,其次,一旦您为表命名,然后在任何地方使用该别名:

        select  a.firstname, a.lastname, count(ba.author_id)
        from author a
        join bookauthor ba on ba.author_id = a.author_id
        group by a.firstname, a.lastname
        

        【讨论】:

          【解决方案5】:

          试试这个 SQL 语法:

          SELECT a.lastname + ', '+ a.firstname, COUNT(b.author_id)
          FROM author AS a
          LEFT JOIN bookauthor AS b ON a.author_id = b.author_id
          GROUP BY a.lastname, a.firstname
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-10-25
            • 2016-05-11
            相关资源
            最近更新 更多