我写了下面的SQL语句并得到结果,当我添加where name = statement时它不识别'name'
SELECT CONCAT( `Surname` , ' ', `firstname` ) AS NAME
FROM Prospects
UNION
SELECT CONCAT( `last_name` , ' ', `first_name` ) AS NAME
FROM customer
ORDER BY name;
答案 0 :(得分:1)
有两种选择。
为每个SELECT添加WHERE子句。在同一查询的WHERE子句中,由分配的别名引用SELECT列表中的表达式结果是不可能的。要在WHERE子句中指定谓词,您需要重复表达式:
SELECT CONCAT(p.surname,' ',p.firstname) AS NAME
FROM Prospects p
WHERE CONCAT(p.surname,' ',p.firstname) = ?
UNION
SELECT CONCAT(c.last_name,' ',c.first_name)
FROM customer c
WHERE CONCAT(c.last_name,' ',c.first_name) = ?
ORDER BY 1
MySQL扩展了SQL标准,并允许HAVING子句引用不在GROUP BY中的非聚合表达式
SELECT CONCAT(p.Surname,' ',p.firstname) AS NAME
FROM Prospects p
HAVING NAME = ?
UNION
SELECT CONCAT(c.last_name,' ',c.first_name) AS NAME
FROM customer c
HAVING NAME = ?
ORDER BY 1
要在WHERE子句中按名称引用别名,可以使用内联视图。但请注意,可能存在显着的性能损失,因为谓词不被推入内联视图。这意味着MySQL将实现视图查询中的所有行作为派生表,然后外部查询将针对派生表运行。不要这样做,特别是对于大桌子:
SELECT v.name
FROM ( SELECT CONCAT(p.Surname,' ',p.firstname) AS NAME
FROM Prospects p
UNION
SELECT CONCAT(c.last_name,' ',c.first_name)
FROM customer c
) v
WHERE v.name = ?
ORDER BY 1
答案 1 :(得分:0)
SELECT
CONCAT( Surname , ' ', firstname ) AS NAME FROM Prospects
UNION
SELECT
CONCAT( last_name , ' ', first_name ) AS NAME FROM customer
WHERE
CONCAT( Surname , ' ', firstname ) = <statement> or
CONCAT( last_name, ' ', firstname ) = <statement>
ORDER BY name;