【问题标题】:Select a field twice with different conditions用不同的条件选择一个字段两次
【发布时间】:2014-05-27 09:11:57
【问题描述】:

我需要选择两个字段但条件不同,我试过这个:

SELECT 
(select my_field from my_table where another_field=1) as column_one,
(select my_field from my_table where another_field=2) as column_two;

但我收到了这个错误:

Subquery returns more than 1 row

有没有办法让它工作?

【问题讨论】:

  • “工作”会是什么样子?
  • 如前所述,将它们选择为 2 列没有多大意义。它们之间没有定义关系。

标签: mysql sql field


【解决方案1】:

在其当前形式中,您可以通过添加 limit 子句使其工作,如下所示:

SELECT 
(select my_field from my_table where another_field=1 limit 1) as column_one,
(select my_field from my_table where another_field=2 limit 1) as column_two;

但是,从逻辑上讲,它没有任何意义,因为没有伴随 ORDER BYlimit 子句不能保证每次查询运行时都会得到特定的结果。

【讨论】:

    【解决方案2】:

    如错误消息所述,其中一个子查询返回多于一行,因此 mysql 无法在单行的单列中输出该子查询的结果。

    确保这两个查询都只返回一行作为结果:

    • select my_field from my_table where another_field=1
    • select my_field from my_table where another_field=2

    【讨论】:

      【解决方案3】:

      它可以返回超过 1 行,所以你应该使用 limit 1

      SELECT (select my_field from my_table where another_field=1 limit 1) as column_one,(select my_field from my_table where another_field=2 limit 1) as column_two;
      

      查询应该是这样的

       select t1.my_field as column_one,t2.my_field as column_two
      from my_table as t1
      left join (select my_field from my_table where another_field=2)  t2 on t1.key_field=t2.key_field
      where t1.another_field=1;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-11-02
        • 2017-08-20
        • 1970-01-01
        • 1970-01-01
        • 2016-11-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多