我在这里有一个关于SQL小提琴的工作示例: http://sqlfiddle.com/#!2/e75d6/34
使用以下查询:
SELECT *
FROM (Orders JOIN
Salesperson ON
Salesperson.ID = Orders.salesperson_id)
JOIN
(SELECT salesperson_id AS sid, MAX( Amount ) AS MaxOrder
FROM Orders
GROUP BY salesperson_id) AS TopOrderAmountsPerSalesperson
ON (TopOrderAmountsPerSalesperson.sid=Orders.salesperson_id AND
TopOrderAmountsPerSalesperson.MaxOrder=Orders.Amount)
但是当我尝试为第一个连接表分配别名时,如下所示:
SELECT *
FROM (Orders JOIN
Salesperson ON
Salesperson.ID = Orders.salesperson_id) AS SalesOrders
JOIN
(SELECT salesperson_id AS sid, MAX( Amount ) AS MaxOrder
FROM Orders
GROUP BY salesperson_id) AS TopOrderAmountsPerSalesperson
ON (TopOrderAmountsPerSalesperson.sid=SalesOrders.salesperson_id AND
TopOrderAmountsPerSalesperson.MaxOrder=SalesOrders.Amount)
我收到语法错误。有什么想法吗?
我使用此SO作为别名连接表的资源: SQL Alias of joined tables
答案 0 :(得分:1)
您可以为整个查询或表名或字段名提供别名,但不能在连接条件上提供别名。请尝试以下示例,并将Orders
表的别名设为SalesOrders
。
SELECT *
FROM Orders AS SalesOrders JOIN
Salesperson ON
Salesperson.ID = SalesOrders.salesperson_id
JOIN
(SELECT salesperson_id AS sid, MAX( Amount ) AS MaxOrder
FROM Orders
GROUP BY salesperson_id) AS TopOrderAmountsPerSalesperson
ON (TopOrderAmountsPerSalesperson.sid=SalesOrders.salesperson_id AND
TopOrderAmountsPerSalesperson.MaxOrder=SalesOrders.Amount)