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 左边
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 左边
解决方案 »
- mysql乱码问题
- php下跑的mysql被新装的数据库完全覆盖,有什么方法可以恢复之前的数据库???
- 求sql语句,包含对特殊字段的sum求和查询
- mysql -u root -h 127.0.0.1 为何会首先解析成 mysql -uroot -hlocalhost 呢?
- mysqldumpslow在那里?我没有找到
- 一个查询语句
- mysql 有视图索引吗?该如何创建?
- MYSQL除了命令行界面以外,有类是 PL/SQL Developer 那样的界面吗?
- 请问各位高手:我现在用(JDBC版本3.08)连接MySQL(版本5.0.1)数据库怎么老是报告连接错误啊!急,在线等待???????
- 新手安装Mysql的问题!! 请大家多帮忙!!
- 学习笔记(shell操作mysql增删改查)
- 在MYSQL中表级完整性约束条件,参照表和被参照表可以是同一个表吗?
如果是MariaDB,可以考虑用开窗函数实现。
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 )