MySQL不重复查询,结果放入另一个表

时间:2018-12-31 12:57:11

标签: mysql distinct

我在tbl1中有两个字段lat和lng。 我只想从两个字段中都选择唯一的数字,我想将结果放在lat和lng相同的字段中的tbl2中。

对不起,我的准确性。

Tbl1是坐标的正方形网格,即,网格的每一行上的纬度坐标相同,而每一列上的经度坐标分别相同。因此结果中有许多不同的经度和纬度坐标。示例-如果网格为100 x 100,则tbl1具有10000行,结果表tbl2具有100行甚至更小的网格2 x 2:

tbl1:  
lat,lng,some more fields,..  
65.123456,24.123456,..  
65.123456,24.123567,..
65.123567,24.123456,..  
65.123567,24.123567,..
tbl2:  
lat,lng  
65.123456,24.123456  
65.123567,24.123567  

我尝试了以下方法:

insert into tbl2 (lat, lng) select distinct lat, lng from tbl1;

我不能使用

.. select distinct lat from tbl1 union select distinct lng from tbl1;

因为它只返回一个字段。

2 个答案:

答案 0 :(得分:1)

带有distinct关键字的插入选择语句应该可以解决问题:

INSERT INTO tbl2
SELECT DISTINT lat, lng
FROM   tbl1

答案 1 :(得分:0)

我发现绕开这个问题的原则是如何吃大象-一次吃一块-即。还有另外两个临时表。

create temporary table t1 (
  id int not null auto_increment primary key ,
  lat double(10,6) not null unique
)  ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci;
create temporary table t2 (
  id int not null auto_increment primary key ,
  lng double(10,6) not null unique
) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci;

insert into t1 (lat) select distinct lat from tbl1;
insert into t2 (lng) select distinct lng from tbl1;

insert into tbl2 select null as id, lat, lng from t1 cross join t2 where t1.id=t2.id;

drop table t1;
drop table t2;

也许可以在这里找到一些更简单复杂的方法?