请教: mysql 同表有两条 service_id 相同数据, flag 不同数据, flag 只有两个值,要求查出值 flag1 存在, flag2 不存在的数据
2021-01-23 13:23:48 +08:00
ouyc
表数据较大,大约一百万条。目前思路是左连接,但会走全表查询,速度很慢
select si1.* from service_info si1 left outer join service_info si2 on si1.service_id = si2.service_id where si1.flag= 'flag1' and si2 .serial_id is null;
SELECT * FROM test3 WHERE flag = 'flag1' AND sid IN ( SELECT sid FROM test3 WHERE flag='flag2' );
zlowly
2021-01-23 19:13:11 +08:00
试试看 group by service_id having count(flag)=sum(strcmp(flag,'flag1'))
zlowly
2021-01-23 19:23:00 +08:00
搞错了,STRCMP(expr1,expr2)相等时才 0,既然只有 flag1,flag2,所以应该直接时 having sum(strcmp(flag,'flag1'))=0
liprais
2021-01-23 19:38:56 +08:00
select * from ( select a, max(case when b = 2 then b end) as flag1, max(case when b = 3 then b end) as flag2 from flags group by a ) dt where flag1 is not null and flag2 is null
行转列过滤一下就行
iamxmz
2021-01-23 21:20:43 +08:00
select service_id, count(flag), sum(flag) from service_info group by service_id having count(flag) = 1 and sum(flag) = flag1
PopRain
2021-01-23 22:07:47 +08:00
select service_id, sum(case when flag='flag1' then 1 else 0 end) as f1, sum(case when flag='flag2' then 1 else 0 end) as f2 from service_info group by service_id having sum(case when flag='flag1' then 1 else 0 end)=1 and sum(case when flag='flag2' then 1 else 0 end) =0
第 1 页 / 共 1 页
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。