我在W3Schools的this示例游乐场页面上尝试了以下SQL。
SELECT CustomerID AS Id, CustomerName AS Customer
FROM Customers
WHERE Customer="Alfreds Futterkiste";
但我得到No value given for one or more required parameters.
作为回应。
如果我使用CustomerName
而不是别名,它就可以工作。
这是游乐场测试页面的失败还是不可能?
答案 0 :(得分:3)
查看您的代码:
SELECT CustomerID AS Id, CustomerName AS Customer
FROM Customers
WHERE Customer="Alfreds Futterkiste";
要为客户表添加别名,您可以执行以下操作:
SELECT c.CustomerID AS Id, c.CustomerName AS Customer
FROM Customers c
WHERE c.CustomerName="Alfreds Futterkiste";
其中c现在是Customers
的别名不能在where子句中使用列别名,因为where子句在select之前执行。
答案 1 :(得分:3)
很丑,但在更大,更复杂的查询中可以很方便
SELECT * FROM
(SELECT CustomerID AS ID, CustomerName AS Customer
FROM Customers) as A
WHERE Customer = "Alfreds Futterkiste";
答案 2 :(得分:2)
在select之前评估WHERE
子句。因此,where子句不知道您使用的别名。
因此您需要使用原始列名:
SELECT CustomerID AS Id, CustomerName AS Customer
FROM Customers
WHERE CustomerName="Alfreds Futterkiste";
如果必须在where子句中使用别名,则可以使用子查询或CTE(过度杀伤并可能导致查询速度变慢):
SELECT * from (
SELECT CustomerID AS Id, CustomerName AS Customer
FROM Customers
) t WHERE Customer = "Alfreds Futterkiste";
答案 3 :(得分:1)
否您无法在WHERE子句中引用列别名。