2

我正在使用 Viescas 的SQL Queries for 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;

我得到类似于下表的内容:

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

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

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

4

1 回答 1

1

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

因此,当您将其与字符串一起用作操作数时,MySql 会将字符串隐式转换为数字(有关详细信息,请检查表达式评估中的类型转换0),结果是任何不以数字开头的字符串,最终结果是0( = false)。如果任何字符串以非零数字部分开头,
结果也可能是1(= ),就像(我怀疑)列的情况一样,你得到.trueCustZipCode1"Address"

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

select CONCAT(customers.CustFirstName, customers.CustLastName) as "Name", 
       CONCAT(customers.CustStreetAddress, customers.CustZipCode, customers.CustState) as "Address",
       ......................................
于 2021-10-23T20:41:36.197 回答