我正在尝试根据一个ID列将两个表连接在一起。联接无法成功进行,因为尽管使用了varchar
,但我无法联接integer
列上的cast()
列。
在第一个表中,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.
奇怪的是,我可以使用完整的数据集执行此连接(显示查询的结果集),但是然后根本无法操作它(例如,对其进行排序,过滤)-我收到一条错误消息,说{{1} }。字符串“ UWM”在数据集中或代码中都没有出现,但我强烈怀疑它与从ERROR: invalid input syntax for integer: "UWM"
到varchar
的split_part强制转换在某处出错有关。
integer
答案 0 :(得分:2)
您需要在连接条件中直接包含当前逻辑:
select *
from fake_receivers r
inner join fake_stations s
on split_part(r.id, '-', 2)::int = s.receiver_sn;