sql - Postgres 在连接时无法识别 CAST 的问题

标签 sql postgresql join casting

我正在尝试根据 ID 列将两个表连接在一起。连接未成功,因为尽管使用了 cast(),但我仍无法将 varchar 列连接到 integer 列。

在第一个表中,ID 列是字符变化的,格式为:XYZA-123456。 在第二个表中,ID 列只是数字:123456

-- TABLE 1
create table fake_receivers(id varchar(11));

insert into fake_receivers(id) values 
('VR2W-110528'),
('VR2W-113640'),
('VR4W-113640'),
('VR4W-110528'),
('VR2W-110154'),
('VMT2-127942'),
('VR2W-113640'),
('V16X-110528'),
('VR2W-110154'),
('VR2W-110528');

-- TABLE 2
create table fake_stations(receiver_sn integer, station varchar);

insert into fake_stations values 
('110528', 'Baff01-01'),
('113640', 'Baff02-02'),
('110154', 'Baff03-01'),
('127942', 'Baff05-01');

我的解决方案是在破折号处拆分字符串,获取破折号后面的数字,并将其转换为整数,以便我可以执行连接:

select cast(split_part(id, '-', 2) as integer) from fake_receivers; -- this works fine, seemingly selects integers

但是,当我实际尝试执行连接时,尽管使用了显式强制转换,但仍收到以下错误:

select cast(split_part(id, '-', 2) as integer), station
        from fake_receivers 
        inner join fake_locations 
        on split_part = fake_locations.receiver_sn -- not recognizing split_part cast as integer! 

>ERROR: operator does not exist: character varying = integer
>Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.

奇怪的是,我可以用我的完整数据集执行此连接(显示查询的结果集),但我根本无法操作它(例如排序、过滤它) - 我收到一条错误消息 ERROR :整数输入语法无效:“UWM”。字符串“UWM”在我的数据集或代码中没有出现,但我强烈怀疑它与从 varcharinteger 的 split_part 转换在某个地方出错有关。

-- Misc. info
select version();
>PostgreSQL 10.5 on x86_64-apple-darwin16.7.0, compiled by Apple LLVM version 9.0.0 (clang-900.0.39.2), 64-bit

编辑:dbfiddle exhibiting behavior

最佳答案

您需要将当前逻辑直接包含在连接条件中:

select *
from fake_receivers r
inner join fake_stations s
    on split_part(r.id, '-', 2)::int = s.receiver_sn;

Demo

关于sql - Postgres 在连接时无法识别 CAST 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53385332/

相关文章:

当用户和设备存储在同一个表中并且关联存储在另一个表中时,SQL/SQLite 检索属于用户的设备列表

PHP/MySQL : Replace multiple queries

sql - 一次使用 charindex、max、substring/right 函数

sql - Arel中 "where exists"怎么办

SQL 替换所有 NULL

postgresql - 在具有 ID 的多个列中查找具有相同值的行

使用带子选择的更新对 PostgreSQL 记录重新排序

mysql - 使用三个表计算行数

python - python 退出并删除类实例

php - 使用行和列索引以表格格式显示数据库表中的数据