首页 文章

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

提问于
浏览
0

假设我有一张 table 和一些像下面这样的值 .

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

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

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 回答

  • 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;
    
  • 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
    

相关问题