我正试图基于一个ID列将两个表连接在一起。联接工作不成功,因为尽管使用了cast()
,但我无法联接integer
列上的varchar
列。
在第一个表中,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: invalid input syntax for integer: "UWM"
。字符串"UWM"在我的数据集中或代码中都没有出现,但我强烈怀疑这与从varchar
到integer
的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展示行为
您需要将当前逻辑直接包含在联接条件中:
select *
from fake_receivers r
inner join fake_stations s
on split_part(r.id, '-', 2)::int = s.receiver_sn;