Sql 返回作者的姓、名&;有多少本书写得超过1本
两个表是book_数据和author_数据Sql 返回作者的姓、名&;有多少本书写得超过1本,sql,database,oracle,Sql,Database,Oracle,两个表是book_数据和author_数据 book\u data有3个字段=author\u id,book\u name,book\u id author\u data有5个字段=author\u id,名,姓,dob,社交 我可以在没有计数的情况下跑步,或者: SELECT first_name, last_name, book_data.author_id FROM author_data INNER JOIN book_data ON book_d
有3个字段=book\u data
,author\u id
,book\u name
book\u id
有5个字段=author\u data
,author\u id
,名
,姓
,dob
社交
SELECT first_name, last_name, book_data.author_id
FROM author_data INNER JOIN book_data
ON book_data.author_id = author_data.author_id
WHERE book_data.author_id = author_data.author_id;
当我加上:
GROUP BY author_id
HAVING COUNT (author_id) > 1)
我收到错误消息。有两件事:{1}当使用JOIN和ON时,不需要编写WHERE子句来连接表。{2} GROUP BY返回“…每个组的一行摘要信息”(请参阅) 测试设置(Oracle 12c) 我们现在有以下作者和书籍:
SQL> select * from authors;
AUTHOR_ID FIRST_NAME LAST_NAME DOB SOCIAL
1 fname1 lname1 01-JAN-01 social1
2 fname2 lname2 02-FEB-02 social2
3 fname3 lname3 03-MAR-03 social3
SQL> select * from books;
AUTHOR_ID BOOK_NAME BOOK_ID
1 book1 5000
2 book2 5001
2 book22 5002
3 book3 5003
3 book33 5004
3 book333 5005
{1} 使用连接。。。ON(无WHERE条款)
{2} 将GROUP BY和HAVING添加到查询中
select
first_name
, last_name
, B.author_id
from authors A
join books B on B.author_id = A.author_id
group by B.author_id
having count( B.author_id ) > 1
;
-- ORA-00979: not a GROUP BY expression
-- works: SELECTed columns are listed in the GROUP BY clause
SQL> select
2 first_name
3 , last_name
4 , B.author_id
5 from authors A
6 join books B on B.author_id = A.author_id
7 group by B.author_id, first_name, last_name
8 having count( B.author_id ) > 1
9 ;
FIRST_NAME LAST_NAME AUTHOR_ID
fname2 lname2 2
fname3 lname3 3
在GROUPBY子句中也添加first_name和last_name。您能告诉我们您得到的错误吗?谢谢。这是一个很好的解释。我在stackoverflow上潜伏了很长时间,但这是我的第一个问题。我感谢你的帮助。
SQL> select
2 first_name
3 , last_name
4 , B.author_id
5 from authors A
6 join books B on B.author_id = A.author_id ;
FIRST_NAME LAST_NAME AUTHOR_ID
fname1 lname1 1
fname2 lname2 2
fname2 lname2 2
fname3 lname3 3
fname3 lname3 3
fname3 lname3 3
select
first_name
, last_name
, B.author_id
from authors A
join books B on B.author_id = A.author_id
group by B.author_id
having count( B.author_id ) > 1
;
-- ORA-00979: not a GROUP BY expression
-- works: SELECTed columns are listed in the GROUP BY clause
SQL> select
2 first_name
3 , last_name
4 , B.author_id
5 from authors A
6 join books B on B.author_id = A.author_id
7 group by B.author_id, first_name, last_name
8 having count( B.author_id ) > 1
9 ;
FIRST_NAME LAST_NAME AUTHOR_ID
fname2 lname2 2
fname3 lname3 3