如何在where子句中将两个不同的sql查询组合成一个主键

时间:2014-04-23 19:16:33

标签: sql database postgresql

我必须在Postgres中执行一个函数,它需要从同一个表中返回两个不同查询的结果,并在同一个表字段(主键)上使用where子句。

具有相同索引号的那些(又名inIndex,outIndex)与一个输入相关,第二个是输出。

示例:

SELECT 
       '9' as inIndex, 
       name as inFieldName 
    from FIELDS 
    where field_id = 1000000005

UNION

SELECT 
       '10' as inIndex, 
       name as inFieldName 
    from FIELDS 
    where field_id = 1000000007;

SELECT  
       '9' as outIndex, 
       name as outFieldName 
    from FIELDS 
    where field_id = 1000000004

UNION 

SELECT  
       '10' as outIndex, 
       name as outFieldName 
    from FIELDS 
    where field_id = 1000000006;

有没有办法将两个查询混合成一个?

如果没有,我如何将两个查询结果都返回到pl / pgsql函数中的一个结果集中?

到目前为止,我已经提出了两个循环,在一个包含3列的自定义类型中添加结果(index,inFiled,outField)。这个程序有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

这样的事情:

SELECT
    '9' AS FieldIndex,
    InFields.name AS InFieldName,
    OutFields.name AS OutFieldName
FROM
    FIELDS AS InFields,
    FIELDS AS OutFields
WHERE
    InFields.field_id = 1000000005
AND OutFields.field_id = 1000000004

UNION

SELECT
    '10' AS FieldIndex,
    InFields.name AS InFieldName,
    OutFields.name AS OutFieldName
FROM
    FIELDS AS InFields,
    FIELDS AS OutFields
WHERE
    InFields.field_id = 1000000007
AND OutFields.field_id = 1000000006

显然你可能需要调整一下......