我正在尝试创建一个查询,列出同一作者的所有书籍。大多数列表只有一本作者的书,但我希望在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
我需要找到一种方法从作者表中获取信息并将其添加到其中。
答案 0 :(得分: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
答案 1 :(得分: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 ....不确定(多年没有使用过它) - 但是您不能只是将原始查询扩展为以下内容:< / p>
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
) - 但我很确定它确实以某种方式支持它....
答案 2 :(得分:0)
只需对每个表进行一次访问即可执行此操作:
SELECT * FROM
(
SELECT AuthorID, BkTitle, AuthFName, AuthLName
,COUNT(*) OVER (PARTITION BY AuthorID)
AS c
FROM BOOK
JOIN AUTHOR USING (AuthorID)
)
WHERE c > 1;