Mysql子查询返回Subquery返回多行错误

时间:2014-01-24 11:50:04

标签: mysql database select subquery

假设我有一张桌子和一些像下面这样的值。

  -----------------------------------------
 | col1    | col2 | col3  | col4  |  col5  |
  ---------|------|-------|-------|--------
 | 6171368 | 1    | TEST  | 12053 | 123456 |
  -----------------------------------------
 | 6171368 | 2    | ABCD  | QWERT |        |
  -----------------------------------------

我想要做的是,如果col5的值为空而不使用conditon exclude col5,我需要获得1行where col2 = 2的值。当我尝试查询时,我收到错误说

  

1242 - 子查询返回超过1行

我的查询是

SELECT col1,col2,col3,col4, 
if (col5 IS NULL or col5 = '' ,
    (
        select col5 from table 
        where col2 = 1 
        group by col1
    ),'')  as col5

2 个答案:

答案 0 :(得分:1)

您希望相关子查询获得该行的有效值col5(假设您有多行)。

SELECT col1, col2, col3, col4, 
       (case when col5 IS NULL
             then (select col5
                   from table t2
                   where t2.col1 = t.col1 and
                         t2.col5 is not null
                   limit 1
                  )
        end) as col5
from table t;

答案 1 :(得分:0)

从错误中,我们可以尝试以下内容:

SELECT col1,col2,col3,col4, 
if (col5 IS NULL or col5 = '' ,
    (
        select col5 from table 
        where col2 = 1 
        group by col1 limit 1
    ),'')  as col5
相关问题