如何得到这样的查询结果?

crmserver 2018-05-22 01:28:02


id type dist location
1 AB 7000 右边
2 A 9000 下面
3 AB 12000 下面
6 A 20000 下面
7 AB 28000 下面
14 AB 7000 左边
4 A 11000 左边
5 AB 22000 左边



当location相同的情况下,取dist最短1条或2条记录,直到type是AB为止,希望得到的结果是:

id type dist location
1 AB 7000 右边
2 A 9000 下面
3 AB 12000 下面
14 AB 7000 左边
...全文
856 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
o前男友o 2018-05-24
  • 打赏
  • 举报
回复
或许有点问题,不过思路你可以这样想。
CREATE TABLE aa (
  id int NOT NULL AUTO_INCREMENT,
  type varchar(10) DEFAULT '',
  dist int DEFAULT '0',
  location varchar(10) DEFAULT '',
  PRIMARY KEY (id)
);
insert  into aa(id,type,dist,location) values (1,'AB',7000,'右边');
insert  into aa(id,type,dist,location) values (2,'A',9000,'下面');
insert  into aa(id,type,dist,location) values (3,'AB',12000,'下面');
insert  into aa(id,type,dist,location) values (6,'A',20000,'下面');
insert  into aa(id,type,dist,location) values (7,'AB',28000,'下面');
insert  into aa(id,type,dist,location) values (14,'AB',7000,'左边');
insert  into aa(id,type,dist,location) values (4,'A',11000,'左边');
insert  into aa(id,type,dist,location) values (5,'AB',22000,'左边');

select * from (
select id,location,type,min(dist) from aa where type='A' group by location
union all 
select id,location,type,min(dist) from aa where type='AB' group by location) m
where m.id not in(
select t1.id
from 
(select id,location,type,min(dist) dist from aa where type='A' group by location) t1
join  
(select id,location,type,min(dist) dist from aa where type='AB' group by location) t2
on t1.location=t2.location where t1.dist>t2.dist )
ACMAIN_CHM 2018-05-23
  • 打赏
  • 举报
回复
依然看不懂逻辑
骏马金龙 2018-05-22
  • 打赏
  • 举报
回复
如果是MySQL,不好直接用sql实现。 如果是MariaDB,可以考虑用开窗函数实现。
crmserver 2018-05-22
  • 打赏
  • 举报
回复
因为前面有AB,所以后面就不再继续了,14 AB 7000 左边
ACMAIN_CHM 2018-05-22
  • 打赏
  • 举报
回复
为什么 4 A 11000 左边 没有了?
  • 打赏
  • 举报
回复
数据库操作不好实现,不好使用分组来实现,非要实现的话用临时表、游标会有点麻烦。 可以在程序中去做遍历组装,这是可以打到你预期的效果。

56,677

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧