0

我研究了这些链接:

简单 SQL 中的子查询返回多行

SQL:错误:用作表达式的子查询返回多行

DatabaseError:用作表达式的子查询返回的不止一行(Django)

错误:用作表达式的子查询返回多行

`单行子查询返回多行`错误不明确

...但是他们似乎在他们的查询中使用了各种过滤,或者他们有子选择,当期望一行时返回多行。我的查询更简单,不应该期望只返回一行(据我所知)。我只是想使用 postgresql-9.1 从视图中全选:

# select * from MYVIEW;
ERROR:  more than one row returned by a subquery used as an expression

而这有效: # SELECT COUNT(*) FROM MYVIEW; count ------- 5 (1 row)

这是我的观点的一般定义(请注意,以下内容仅供参考我从中选择的内容,而不是收到错误的内容。仅在运行上面发布的“全选”时收到错误) :

CREATE VIEW MYVIEW(ID1, ID2, ID3, KEY1, KEY2, ID4, TXT1, ID5, LOC1) AS 
SELECT 
    TABLE1.ID1, 
    (SELECT VALUE FROM TABLE2 WHERE TABLE3.TABLE3_ID = TABLE2.TABLE3_ID AND NAME = 'blah1' ) as ID2,
    (SELECT VALUE FROM TABLE2 WHERE TABLE3.TABLE3_ID = TABLE2.TABLE3_ID AND NAME = 'blah2' ) as ID3,
    (SELECT VALUE FROM TABLE2 WHERE TABLE3.TABLE3_ID = TABLE2.TABLE3_ID AND NAME = 'blah3') as KEY1,
    (SELECT VALUE FROM TABLE2 WHERE TABLE3.TABLE3_ID = TABLE2.TABLE3_ID AND NAME = 'blah4') as KEY2, 
    TABLE4.ID6,
    TABLE4.NAME,
    ID5,
    coalesce(
        (SELECT VALUE FROM TABLE5 WHERE TABLE5.ID5 = TABLE6.ID5 AND NAME = 'BLAH5'), 
        (SELECT VALUE FROM TABLE7 WHERE TABLE7.ID6 = TABLE6.ID6 AND NAME = 'BLAH5' )
    ) as LOC1 
FROM TABLE3, TABLE6, TABLE1, TABLE4, TABLE8 
WHERE 
    TABLE3.TABLE8_ID = TABLE8.TABLE8_ID AND 
    TABLE3.ID1 = TABLE1.ID1 AND 
    TABLE8.TABLE8_ID = TABLE4.TABLE8_ID AND 
    TABLE4.ID6 = TABLE6.ID6 AND 
    TABLE6.TABLE3_ID = TABLE3.TABLE3_ID and 
    TABLE8.NAME = 'BLAH6' and 
    TABLE8.on = true and 
    TABLE4.ON = true and 
    TABLE6.ON = true and 
    TABLE1.ON = true AND 
    TABLE3.ON = TRUE;
4

2 回答 2

2

事实证明,“子查询返回多行”消息的来源是视图中有重复的条目。从视图的源表中删除冗余记录后,就不会遇到错误。

于 2013-07-19T20:27:10.503 回答
2

我的猜测是,没有深入查看您发布的代码块,您的代码中嵌套了一个 SUB-SELECT 语句,它试图选择多个列。使用 SUB-SELECT(嵌套在查询中的 SELECT),您只能将一列作为结果返回到外部查询。

于 2013-07-18T16:40:22.677 回答