2

我正在尝试创建一个查询,该查询将列出同一作者的所有书籍。大多数列表只有一位作者的一本书,但我希望在 db 中列出多本书的作者为该作者显示这些书。

我有两张桌子:

  • -AuthorID, BkTitle
  • 作者——AuthorID, AuthFName, AuthLName

我希望对结果进行排序,AuthLName并且报告包含 db 中具有相同authorid.

想要的示例结果:

 AUTHORID BKTITLE           AUTHFNAME     AUTHLNAME
--------- ----------------- ------------  -----------
    504   KNIGHT FREEDOM     Chris        Feehan
    504   KNIGHT SHOWDOWN    Chris        Feehan

目前,我有以下代码:

select AUTHORID, BKTITLE
from BOOK 
where AUTHORID in
    (select AUTHORID from
       (select AUTHORID, 
               count(*) as BOOK_COUNT
        from BOOK
        group by AUTHORid
        order by AUTHORid )
     where BOOK_COUNT >= 2);

这使:

  AUTHORID BKTITLE
---------- --------------------
       504 KNIGHT FREEDOM
       504 KNIGHT SHOWDOWN

我需要找到一种从作者表中获取信息并将其添加到其中的方法。

4

3 回答 3

2

这应该这样做:

SELECT b.AUTHORID, b.BKTITLE, a.AUTHFNAME, a.AUTHLNAME
FROM BOOK b
  INNER JOIN AUTHOR a
    ON b.AUTHORID = a.AUTHORID
AND b.AUTHORID IN
(
  SELECT AUTHORID
  FROM BOOK
  GROUP BY AUTHORID
  HAVING COUNT(AUTHORID) > 1
)
ORDER BY a.AUTHLNAME, a.AUTHFNAME
于 2012-04-14T19:39:21.243 回答
1

怎么样 - 更新为首先使用 CTE(通用表表达式)来确定哪些作者在数据库表中拥有不止一本书BOOK,然后仅列出这些作者及其书籍:

;WITH AuthorsWithMoreThanOneBook AS
(
    SELECT AUTHORID, BOOK_COUNT = COUNT(*)
    FROM BOOK
    GROUP BY AUTHORID
    HAVING BOOK_COUNT > 1)
)
SELECT
    b.AUTHORID, b.BKTITLE, a.AuthFName, a.AuthLName
FROM
    BOOK b
INNER JOIN
    AUTHOR a ON b.AuthorID = a.AuthorID
INNER JOIN 
    AuthorsWithMoreThanOneBook A2 ON a.AuthorID = A2.AuthorID
ORDER BY
    a.AuthLName, a.AuthFName

更新:好的,您正在使用 Oracle .... 不确定(已经很久没有使用它了) - 但您不能像这样扩展您的原始查询:

select bk.AUTHORID, bk.BKTITLE, a.AUTHORFNAME, a.AUTHORLNAME
from BOOK AS bk
INNER JOIN AUTHOR AS a ON a.AUTHORID = bk.AUTHORID
where bk.AUTHORID in
    (select AUTHORID from
       (select AUTHORID, 
               count(*) as BOOK_COUNT
        from BOOK
        group by AUTHORid
        order by AUTHORid )
     where BOOK_COUNT >= 2);

不确定Oracle是否/如何支持这些表别名(BOOK AS bk)-但我很确定它确实以某种方式支持它......

于 2012-04-14T19:39:49.977 回答
0

您可以通过对每个表的一次访问来执行此操作:

SELECT * FROM
(
  SELECT AuthorID, BkTitle, AuthFName, AuthLName
        ,COUNT(*) OVER (PARTITION BY AuthorID)
         AS c
  FROM BOOK
  JOIN AUTHOR USING (AuthorID)
)
WHERE c > 1;
于 2012-04-16T06:02:37.343 回答