Specifying data type of columns in a values subquery

烈酒焚心 提交于 2019-12-20 02:36:09

问题


Is there a way to specify the data types of the columns in a values subquery? Something like (values (...)) as tmp_name (colname::type)?

Contrived Example

Say I have a table with a uuid column:

/* setup */
create table foo (id uuid);
insert into foo values 
    ('aaaabbbbccccddddeeeeffff00001111'),
    ('aaaabbbbccccddddeeeeffff00002222'),
    ('aaaabbbbccccddddeeeeffff00003333');


If I try to join against it using a values subquery, postgres assumes the column is type text and throws a type error (even though the same strings worked for direct insertion into the uuid column) :

select foo.id from foo 
inner join (values 
    ('aaaabbbbccccddddeeeeffff00001111'),
    ('aaaabbbbccccddddeeeeffff00000000'))
as tmp (id) on foo.id = tmp.id;

ERROR:  operator does not exist: uuid = text
LINE 5:     as tmp (id) on foo.id = tmp.id;
                                  ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.


Explicitly casting each value:

It works if I add the explicit cast to the values themselves, but it would be nice not to have to cast every single value and just specify the datatype of the column as a whole:

select foo.id from foo 
inner join (values
    ('aaaabbbbccccddddeeeeffff00001111'::uuid),
    ('aaaabbbbccccddddeeeeffff00000000'::uuid))
as tmp (id) on foo.id = tmp.id;

回答1:


You can cast once on the join predicate:

select foo.id from foo 
inner join (values 
    ('aaaabbbbccccddddeeeeffff00001111'),
    ('aaaabbbbccccddddeeeeffff00000000'))
as tmp (id) on foo.id = tmp.id::uuid;


来源:https://stackoverflow.com/questions/47560769/specifying-data-type-of-columns-in-a-values-subquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!