两个表是book_data& author_data。
book_data
有3个字段= author_id
,book_name
,book_id
。author_data
有5个字段= author_id
,first_name
,last_name
,dob
,social
。我可以在没有COUNT或HAVING的情况下运行:
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)
我收到错误消息。
答案 0 :(得分:0)
两件事:{1}当您使用JOIN和ON时,您不需要编写WHERE子句来连接表。 {2} GROUP BY返回" ...每组的一行摘要信息" (见documentation)
测试设置(Oracle 12c)
create table authors (
author_id number primary key
, first_name varchar2(64)
, last_name varchar2(64)
, dob date
, social varchar2(4000)
);
create table books (
author_id references authors
, book_name varchar2(256)
, book_id number generated always as identity start with 5000
);
begin
insert into authors ( author_id, first_name, last_name, dob, social )
values ( 1, 'fname1', 'lname1', date'2001-01-01', 'social1') ;
insert into authors ( author_id, first_name, last_name, dob, social )
values ( 2, 'fname2', 'lname2', date'2002-02-02', 'social2') ;
insert into authors ( author_id, first_name, last_name, dob, social )
values ( 3, 'fname3', 'lname3', date'2003-03-03', 'social3') ;
end ;
/
begin
insert into books ( author_id, book_name ) values ( 1, 'book1' );
insert into books ( author_id, book_name ) values ( 2, 'book2' );
insert into books ( author_id, book_name ) values ( 2, 'book22' );
insert into books ( author_id, book_name ) values ( 3, 'book3' );
insert into books ( author_id, book_name ) values ( 3, 'book33' );
insert into books ( author_id, book_name ) values ( 3, 'book333' );
end;
/
我们现在有以下作者和书籍:
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}使用JOIN ... ON(无WHERE子句)
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
{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