【问题标题】:Mysql subquery returns Subquery returns more than 1 row errorMysql子查询返回子查询返回多于1行错误
【发布时间】:2014-02-15 09:40:51
【问题描述】:

假设我有一个表格和一些值,如下所示。

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

我想要做的是如果col5 的值为空而不使用where 条件排除where col2 = 2,我需要获取1 行的col5 的值。当我尝试查询时,我收到一条错误消息

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

【问题讨论】:

    标签: mysql database select subquery


    【解决方案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;
    

    【讨论】:

      【解决方案2】:

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

      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
      

      【讨论】:

        猜你喜欢
        • 2017-05-29
        • 1970-01-01
        • 2016-07-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多