Postgresql:指定values子查询中列的数据类型

时间:2017-11-29 19:57:49

标签: sql postgresql-9.1 postgresql-9.3

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

这样的东西

Contrived Example

假设我有一个包含uuid列的表格:

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


如果我尝试join使用values子查询对其进行反对,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;

1 个答案:

答案 0 :(得分:1)

您可以在连接谓词上投射一次:

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