我在大学的一个SQL班,我们正在使用PSQL。
供参考的表格。
Table "public.author"
Column | Type | Modifiers
------------+---------+-----------
au_id | numeric | not null
first_name | text | not null
last_name | text | not null
year_born | numeric | not null
Table "public.book"
Column | Type | Modifiers
--------+---------+-----------
title | text | not null
year | numeric | not null
isbn | text | not null
pub_id | numeric | not null我遇到的问题是:显示1990年至1993年出版的所有书籍的作者姓名、书名和出版年份。将作者名称显示为“最后”、“第一”(中间有逗号和空格)。按出版年份对输出进行排序。
输出:
select concat(last_name, ',', first_name) as name, title, year from author, book where year >= 1990 and year <= 1993 group by year order by year;错误:列"author.last_name“必须出现在GROUP子句中,或者在聚合函数行1中使用:选择concat(last_name,',',first_name)作为名称、标题、ye.
我明白这是说我需要按顺序订购,但问题是我按年范围订购。
发布于 2018-07-08 09:28:32
错误:只有当您有一个或多个聚合列(如sum、max、min、avg)并且需要在GROUP BY子句中添加所有其他列时,才需要使用GROUP BY子句。
您尝试过的内容:交叉连接所有的书籍和所有作者,并显示一个大的结果集。我假设图书的author_id在表书的pub_id列中,id在author.au_id中。如果不使用INNER JOIN ...,则可以将联接条件放入WHERE语句:WHERE author.au_id=book.pub_id and year >= 1990 and year <= 1993中。
发布于 2018-07-08 09:54:34
在对两个表进行查询时,请使用“”引用特定的表。当你得到一个错误
错误:"author.last_name“列必须出现在GROUP子句中
在group by语句中也包括author.last_name,就像我在下面的代码中包含了Author_name一样。
select concat(author.last_name, ',', author.first_name) as
Author_name,book.title,book.year
from author,book
where book.year >= 1990 and book.year <= 1993
group by book.year,book.title,Author_name
order by book.year asc;发布于 2018-07-08 11:43:28
您所拥有的两个表不足以回答这个问题。你需要一个连接表,每一位作者和一本书都有一行。让我把这叫做book_authors。
然后,将此查询编写为:
select concat(a.last_name, ',', a.first_name) as name, b.title, b.year
from author a join
book_authors ba
on a.au_id = ba.au_id join
book b
on b.isbn = ba.isbn
where b.year >= 1990 and b.year <= 1993
order by b.year;备注:
FROM子句中使用逗号。始终使用正确、显式、标准的 JOIN语法。如果2018年的一堂课在教过时的语法,那是非常非常可悲的。GROUP BY。https://stackoverflow.com/questions/51228698
复制相似问题