获得质量更好的领域的记录

时间:2015-03-19 15:19:49

标签: mysql select having

我有上表

 create table wardrive 
    (
    id int not null auto_increment,
    mac varchar(50) not null,
    ssid varchar(100),
    lat varchar(20),
    lon varchar(20),
    rssi int,
    quality int,
    channel int,
    privacy varchar(20),
    hora varchar(30),
    primary key(id)
    )

在这张桌子上,我有一些无线接入点的mac地址,坐标,信号质量等等。 我需要获得每个mac的3,4,5条记录,它们具有更好的信号质量,并获得坐标(lat,lon)

select mac, lat, lon, quality
from wardrive
group by mac, quality;

我尝试使用max进行过滤,但没有成功......我在想...它只会返回更好的质量......而不是3,4更好的结果

2 个答案:

答案 0 :(得分:0)

我认为排名功能应该适合你

SET @rank:=1; 
SET @mac := null;
SELECT * FROM 
( SELECT @rank = IF(@mac = mac , @rank+1, 1) as rank, 
 @mac:=mac as mac , lat, lon, quality
 FROM wardrive
 ORDER BY mac, quality
) AS t WHERE rank <=3 ; ## the number you have to have

答案 1 :(得分:0)

这解决了我的问题

set @num := 0, @mac := '';

select ssid, mac, quality, lat, lon, privacy
from 
(
   select *,
      @num := if(@mac = mac, @num + 1, 1) as row_number,
      @mac := mac as dummy
  from wardrive
  order by mac, quality desc
) as w 
where w.row_number <= 3
order by quality desc;

实施例

mac        quality       lat           lon        privacy
'00:1F:6D:A7:D4:D6','80','-21.116403','-47.78662','WEP'
'00:1F:6D:A7:D4:D6','79','-21.116382','-47.786582','WEP'
'00:1F:6D:A7:D4:D6','69','-21.116508','-47.786841','WEP'
'00:2A:E7:B3:DE:32','69','-21.120032','-47.787511','WPA'
'00:2A:E7:B3:DE:32','67','-21.116821','-47.787466','WPA'
'00:2A:E7:B3:DE:32','54','-21.116781','-47.787468','WPA'
'0A:22:BC:A8:E2:EA','84','-21.117334','-47.786619','WPA2'
'0A:22:BC:A8:E2:EA','84','-21.117396','-47.786617','WPA2'
'0A:22:BC:A8:E2:EA','68','-21.117823','-47.786794','WPA2'
'54:E6:52:F5:1C:32','24','-21.119308','-47.787254','WPA2'
'54:E6:52:F5:1C:32','24','-21.119308','-47.787254','WPA2'
'54:E6:52:F5:1C:32','10','-21.117118','-47.78716','WPA2'
'5C:52:1F:1B:84:50','38','-21.117697','-47.786715','WPA2'
'5C:52:1F:1B:84:50','38','-21.117823','-47.786794','WPA2'