SQL搜索查询在FROM子句'中返回'语法错误

时间:2015-03-08 00:47:31

标签: sql

我是初学者并且正在尝试学习SQL。在我正在进行的练习中,我输入了以下查询,并在FROM子句#39中出现错误'语法错误;

select orders.customerid, customers.customername, count(orders.customerid)
from orders
join customers on customers.customerid = orders.customerid
group by orders.customerid
order by count(orders.customerid)

1 个答案:

答案 0 :(得分:2)

在W3Schools SQL中,需要指定与join关键字一起使用的连接类型(内部,左侧,右侧)。

使用join customers on customers.customerid = orders.customerid会在FROM子句中出现语法错误。

将联接更改为inner join可修复该错误,但还有另一个问题,即group by语句中缺少的列:您尝试执行的查询不包含指定的表达式'customername '作为聚合函数的一部分。

修复后,查询将如下所示:

select orders.customerid, customers.customername, count(orders.customerid)
from orders
inner join customers on customers.customerid = orders.customerid
group by orders.customerid, customers.customername
order by count(orders.customerid);

但是,如果您想要返回所有客户,无论是否有任何订单,您都应该更改查询以使用左连接:

select orders.customerid, customers.customername, count(orders.customerid)
from customers
left join orders on customers.customerid = orders.customerid
group by orders.customerid, customers.customername
order by count(orders.customerid);

另外,这可能是获取别名使用的好时机:

select o.customerid, c.customername, count(o.customerid) as count_of_orders
from customers as c
left join orders as o on c.customerid = o.customerid
group by o.customerid, c.customername
order by count(o.customerid);

查看查询变短了多少? :)