MySQL: 在一个有聚合函数的select中,如何连接两个不在聚合函数中的列?

MySQL: In a select with aggregate functions, how to join two columns not in aggregate functions?

我正在使用 Viescas 的 SQL Mere Mortals 查询及其数据集。

如果我运行他的代码:

select customers.CustFirstName || " " || customers.CustLastName as "Name", 
customers.CustStreetAddress || "," || customers.CustZipCode || "," || customers.CustState as "Address",
count(engagements.EntertainerID) as "Number of Contracts",
sum(engagements.ContractPrice) as "Total Price",
max(engagements.ContractPrice) as "Max Price"
from customers
inner join engagements
on customers.CustomerID = engagements.CustomerID
group by customers.CustFirstName, customers.custlastname,
customers.CustStreetAddress,customers.CustState,customers.CustZipCode
order by customers.CustFirstName, customers.custlastname;

我得到如下内容 table:

姓名地址合约数量总价最高价

0   1   7   8255.00 2210.00
0   1   11  11800.00    2570.00
0   1   10  12320.00    2450.00
0   1   8   10795.00    2750.00
0   1   8   25585.00    14105.00
0   1   6   7560.00 2300.00

但是,第一行应该在名称列中输出 Carol Viescas...为什么我们得到的是零?

运算符 || 是 MySql 中的 Logical OR 运算符(自版本 8.0.17 起已弃用),而不是连接运算符。

因此,当您将它与字符串一起用作操作数时,MySql 会将字符串隐式转换为数字(查看 Type Conversion in Expression Evaluation 了解详细信息),结果为 0不以数字开头的字符串,最终结果为 0 (= false).
如果任何字符串以非零数字部分开头,结果也可能是 1 (= true),就像(我怀疑)列 CustZipCode 的情况一样,你得到 1"Address".

如果你想连接字符串,你应该使用函数 CONCAT():

select CONCAT(customers.CustFirstName, customers.CustLastName) as "Name", 
       CONCAT(customers.CustStreetAddress, customers.CustZipCode, customers.CustState) as "Address",
       ......................................