在值子查询中指定列的数据类型

Specifying data type of columns in a values subquery

有没有办法在 values 子查询中指定列的数据类型?类似于 (values (...)) as tmp_name (colname::type)?

人为的例子

假设我有一个 table 和 uuid 列:

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


如果我尝试使用 values 子查询 join 反对它,postgres 假定该列是类型 text 并抛出一个 类型错误 (即使相同的字符串用于直接插入 uuid 列):

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.


显式转换每个值:

如果我将显式强制转换添加到值本身,它会起作用,但最好不要强制转换每个值,只需指定整个列的数据类型:

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

您可以对连接谓词进行一次转换:

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