我有一张表call_memmo
,其中chance_no
列为int
。还有其他两列is_group1
和is_group2
都是tinyint
类型且互斥。所以我想在一次查询中为max(chance_no)
和is_group1=1
提取is_group2=1
。
我试过了这个查询
select if(is_group1 <> 0, max(chance_no), 0) as max_chance_group1,
if(is_group2 <> 0, max(chance_no), 0) as max_chance_group2
from call_memmo
结果为
max_chance_group1 max_chance_group2
0 3
输出错误,因为max_chance_group1
应该是2
。
然后我尝试了这个查询
select (select max(chance_no) from call_memmo where is_group1 = 1) as max_chance_group1,
(select max(chance_no) from call_memmo where is_group2 = 1) as max_chance_group2
from call_memmo group by is_group1, is_group2
这正确地提供输出但是有多条记录
max_chance_group1 max_chance_group2
2 3
2 3
我知道我使用的查询不正确,所以任何人都可以帮助我更好的方法并获得单行输出,以便我可以跳过迭代吗?
答案 0 :(得分:1)
select (select max(chance_no) from call_memmo where is_group1 = 1) as max_chance_group1,
(select max(chance_no) from call_memmo where is_group2 = 1) as max_chance_group2
from call_memmo limit 1
或者您可以将新列分组为
select (select max(chance_no) from call_memmo where is_group1 = 1) as max_chance_group1,
(select max(chance_no) from call_memmo where is_group2 = 1) as max_chance_group2 from call_memmo group by max_chance_group1,
max_chance_group2
答案 1 :(得分:1)
尝试不需要分组
select (select max(chance_no) from call_memmo where is_group1 = 1) as max_chance_group1,
(select max(chance_no) from call_memmo where is_group2 = 1) as max_chance_group2