PostgreSQL:`VIEW` returns 没有包含 `SPLIT_PART()` 列的行

PostgreSQL: `VIEW` returns no rows with `SPLIT_PART()` columns

问题描述:

大家好,我在查询 VIEW 时遇到了一些问题,该 VIEW 的列部分是 og table 列上 SPLIT_PART() 函数的结果;我创建了如下视图:

CREATE VIEW ClientsAddressList(Client_ID, FirstName, LastName, ResidenceAddress, City, PostalCode, Province) AS
SELECT Client_ID, 
       FirstName, 
       LastName, 
       SPLIT_PART(Address, '-', 1) AS ResidenceAddress, 
       SPLIT_PART(Address, '-', 2) AS City, 
       SPLIT_PART(Address, '-', 3) AS PostalCode,     
       SPLIT_PART(Address, '-', 4) AS Province
FROM Clients;

我的目的是将结构化属性(Clients.Address定义为一个字符串VARCHAR(255)),其中包含与客户住所有关的所有信息,分成几列单独查询(例如SELECT FirstName, LastName FROM ClientAddressList WHERE City LIKE 'N%';SELECT Client_ID FROM ClientAddressList WHERE PostalCode = '82305';).

我的经历:

客户端 table 包含一个测试行:

Client_ID FirstName LastName ResidenceAddress City PostalCode Province
00451 Ezio Auditore Via dei Banchi 45 - Florence - 50123 - Florence Florence 50123 Florence

所以我的 VIEW 有这一行:

Client_ID FirstName LastName ResidenceAddress City PostalCode Province
00451 Ezio Auditore Via dei Banchi 45 Florence 50123 Florence

我试过:

SELECT Client_ID, FirstName, LastName
FROM ClientsAddressList
WHERE City = 'Florence'

它returns没有结果:

Client_ID FirstName LastName ResidenceAddress City PostalCode Province

但是如果我查询不是 SPLIT_PART() 结果的列,它会起作用:

SELECT Client_ID, FirstName, LastName, City
FROM ClientsAddressList
WHERE Client_ID = '00451'
Client_ID FirstName LastName City
00451 Ezio Auditore Florence

我的期望:

我会 WHERE 子句工作并且 returns 值甚至在 SPLIT_PART() 结果列上:

SELECT Client_ID
FROM ClientAddressList
WHERE PostalCode LIKE = '%123'
Client_ID
00451

有人可以解释一下可能是什么问题吗?非常感谢!

正如 sticky bit 所写:值周围有空格。有两种方法可以解决这个问题。一种方法是在视图中的表达式周围打一个 trim() :

trim(SPLIT_PART(Address, '-', 2)) AS City, 

另一种选择是使用适当的正则表达式来拆分信息以在拆分过程中删除空格:

select client_id, 
       firstname, 
       lastname,
       address[1] as residenceaddress,
       address[2] as city,
       address[3] as postalcode,
       address[4] as province
from (
  select client_id, firstname, lastname,
         regexp_split_to_array(residenceaddress, '\s*-\s*') as address      
  from clients
) t  

Online example


在长 运行 中,您应该通过正确规范化数据模型并将这些值存储在单独的列中来修复数据模型。我不知道在意大利有多少城市名称包含破折号,但在德国,这种模式很快就会被城市名称打破,例如“Garmisch-Partenkirchen”或“Leinfelden-Echterdingen”