【问题标题】:How can I return 1 row from a subquery in select statement if subquery has more than 1 result?如果子查询有超过 1 个结果,如何从 select 语句中的子查询返回 1 行?
【发布时间】:2018-05-03 07:37:18
【问题描述】:

我有这个问题:

select a.*, b.*, (select c.* from tableC c where c.id_tableA = a.id) from tableA a inner join tableB b on a.id = b.id_tableA where b.id_user = 50;

子查询(即 tableC)按预期返回超过 1 行。如何从 tableC 中只返回 1 行以便它可以与查询的其余部分匹配?

到目前为止,我已经尝试过:

(select c.* from tableC c where c.id_tableA = a.id limit 1) 

它没有像mysql所说的那样工作:

"操作数应包含 1 列"

【问题讨论】:

    标签: mysql subquery limit


    【解决方案1】:

    你混合了两件事。 SELECT 列表中的标量子查询应该只返回一个值(行和列)。使用LIMIT 1 将获得一行,但仍然有很多列。 所以你可以指定列名:

    select a.*, b.*,
      (select c.col_name from tableC c where c.id_tableA = a.id order by .. limit 1) 
    from tableA a 
    inner join tableB b on a.id = b.id_tableA 
    where b.id_user = 50;
    

    或者使用普通的JOIN:

    select a.*, b.*, c.*
    from tableA a
    inner join tableB b 
      on a.id = b.id_tableA 
    left join tableC c
      on c.id_tableA = a.id
    where b.id_user = 50;
    

    【讨论】:

      【解决方案2】:

      如果表 C 中的列 id 是主键,那么它应该没有问题 但如果不是,请尝试添加另一个条件来过滤您的子查询结果,例如,

      例如这里是开始日期:

      SELECT a.column_1, b.column_2, 
              (SELECT column_3 FROM tableC  
              WHERE (id = a.id 
              AND (start_date = (SELECT MAX(b.start_date) 
                   from tableC as c
                   where a.id = c.id ))) AS column_3
      FROM tableA as a INNER JOIN
           tableB as b ON b.id = a.id
      WHERE b.id_user = 50;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多