我需要选择两个但具有不同条件的字段,我试过这个:
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
有没有办法使这项工作?
答案 0 :(得分:0)
它可以返回超过1行,因此您应该使用限制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;
答案 1 :(得分:0)
如错误消息所述,其中一个子查询返回多行,因此mysql无法在单行的单个列中输出该子查询的结果。
确保这两个查询仅返回一行:
select my_field from my_table where another_field=1
select my_field from my_table where another_field=2
答案 2 :(得分:0)
在目前的形式中,您可以通过添加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;
但是,从逻辑上讲它没有任何意义,因为没有附带limit
的{{1}}子句不能保证每次查询运行时都有特定的结果。