将 char var 转换为整数以用于连接

Convert char var to integer for use in join

我正在尝试使用我们的 postgres 数据库通过 crystal 向 运行 发送报告。

我的SQL长得像

SELECT 
    slcnote.note_date, 
    slcnote.account, 
    customer.name, 
    slcnote.reference,
    slcnote.operator,
    salesman.name,  
    slcnote.system_date,
    slcnote.note_type, 
    slcnote.note_note,
                CAST(salesman.code as integer)
FROM   
   slcnote
    Left JOIN customer ON slcnote.account=customer.account
    left JOIN salesman ON slcnote.operator=salesman.code
 ORDER BY "slcnote"."note_date"

但是它似乎没有将销售员代码转换为整数。我在 Crystal 报告中遇到以下错误消息:

--------------------------- Crystal Reports --------------------------- 
Failed to retrieve data from the database. 
Details: 42883:
ERROR: operator does not exist: integer = character varying; 
Error while executing the query 
[Database Vendor Code: 7 ] 
--------------------------- OK ---------------------------

感谢帮助

克里斯

您的问题是您在 SELECT 子句中将 salesman.code 转换为整数,但在 ON 子句中没有。因此,查询试图通过将 integerVARCHAR 进行比较来加入 tables,这会生成错误消息。

要解决您眼前的问题,您需要在 ON 子句中执行转换:

SELECT * 
FROM slcnote
    LEFT JOIN salesman ON CAST(salesman.code AS INT) = slcnote."operator"

然而,如评论中所述,此查询的性能将很糟糕。如果您无法更改 table,您是否能够创建执行转换的物化视图?这可能会有所帮助。您还应该看看 能够更改 table 的人是否会这样做,并引用这些性能问题。