正确加入查询 - SQL

Join queries properly - SQL

我有两个 table,分别是 BooksCo-author。我想加入他们,让 table 显示在“所需输出”下。我是 SQL 的新手,我正在努力加入我所做的两个查询...

书籍:

ISBN title author
1111 Book1 author1
2222 Book2 author2
3333 Book3
4444 Book4 author3

合著者:

id author book(isbn)
1 author_x 4444
2 author_y 1111
3 author_z 2222
4 author_w 4444

期望的输出:

title has_author count_co_author
Book1 1 1
Book2 1 1
Book3 0 0
Book4 1 2

我有以下疑问:

SELECT b.title, count(c.book)
FROM Books b
LEFT JOIN Coauthor c ON b.isbn = c.book
GROUP BY b.title

returns 列 count_co-author

以及对列 has_author 的另一个查询:

SELECT 
    b.title, 
    CASE 
        WHEN b.author IS NULL 
            THEN 0 
            ELSE 1 
    END AS 'Has author'
FROM Books b

如何组合它们?

select  title, has_auther, count_co-author, 
from 
( 
  (
    SELECT
      b.title,
      count(c.book) as count_co-author
    FROM Books b 
    LEFT JOIN Coauthor c ON b.isbn = c.book
    GROUP BY b.title
  ) as t1, 
  (
    SELECT 
      b.title, 
      CASE WHEN b.author IS NULL 
        THEN 0 
        ELSE 1 
    END AS has_auther
    FROM Books b
  ) as t2
)

试试这个

SELECT 
    b.title, 
    CASE
        WHEN b.author IS NULL
            THEN 0
            ELSE 1
    END AS has_author,
    count(c.book) as count-coauthor
FROM
    Books b
LEFT JOIN
    Coauthor c
ON
    b.isbn = c.book
GROUP BY
    b.title

应该工作IG

Select本书及加入合著者数:

select
  b.title,
  case when b.author is null then 0 else 1 end as has_author,
  coalesce(c.cnt, 0) as count_co_author
from books b
left outer join
(
  select book, count(*) as cnt
  from co_author
  group by book
) c on c.book = b.isbn
order by b.title;

或 select 来自书籍并在子查询中获取共同作者计数:

select
  b.title,
  case when b.author is null then 0 else 1 end as has_author,
  (
    select count(*)
    from co_author c
    where c.book = b.isbn
  ) as count_co_author
from books b
order by b.title;