关键字组附近的语法不正确

时间:2011-04-07 08:23:45

标签: sql

你好我正在写一个sql查询但是我在GROUP BY的行上遇到语法错误。可能是什么问题。

SELECT au_lname, au_fname, t.title_id
from authors As a INNER JOIN
titleauthor As ta On a.au_id = ta.au_id INNER JOIN
titles As t On t.title_id = ta.title_id
ORDER BY au_lname, au_fname
GROUP BY au_lname

2 个答案:

答案 0 :(得分:7)

在ORDER BY之前放置GROUP BY。此外,select中包含的所有字段必须位于GROUP BY语句中,或者位于聚合函数内。

试试这个:

SELECT au_lname, au_fname, t.title_id
from authors As a INNER JOIN
titleauthor As ta On a.au_id = ta.au_id INNER JOIN
titles As t On t.title_id = ta.title_id
GROUP BY au_lname, au_fname, t.title_id
ORDER BY au_lname, au_fname

如果您只是想摆脱重复的结果,也可以使用关键字DISTINCT:

SELECT DISTINCT au_lname, au_fname, t.title_id
from authors As a INNER JOIN
titleauthor As ta On a.au_id = ta.au_id INNER JOIN
titles As t On t.title_id = ta.title_id
ORDER BY au_lname, au_fname

答案 1 :(得分:0)

select语句的一般语法是

SELECT select_list
[INTO new_table_]
FROM table_source
[WHERE search_condition]
[GROUP BY group_by_expression]
[HAVING search_condition]
[ORDER BY order_expression [ASC | DESC] ;

所以在你的情况下

SELECT au_lname, au_fname, t.title_id
from authors As a INNER JOIN
titleauthor As ta On a.au_id = ta.au_id INNER JOIN
titles As t On t.title_id = ta.title_id
GROUP BY au_lname
ORDER BY au_lname, au_fname