提高mysql查询的准确性

时间:2012-12-17 08:12:21

标签: mysql join

有没有办法提高以下查询的准确性?

SELECT DISTINCT a.localgeo, a.foreigngeo, b.lat, b.lng, c.lat, c.lng
FROM tbl_correlateddata a
JOIN tbl_geodetail b ON a.localgeo = b.code
JOIN tbl_geodetail c ON a.foreigngeo = c.code

我正在访问一个包含2个国家/地区代码的表格

localgeo|foreigngeo
--------------------
JP      |AD
JP      |AD
US      |HK
AD      |JP
HK      |US
AD      |JP
CN      |US

并尝试用另一个表中的经度和纬度值填充它

code|lat|lng
------------
JP  |1  |2
US  |3  |3
HK  |1  |4
AD  |3  |4
CN  |4  |4

结果如下所示

localgeo|lat|lng|foreigngeo |lat|lng|
------------------------------------
JP      |1  |2  |AD         |3  |4
US      |3  |3  |HK         |1  |4
HK      |1  |4  |US         |3  |3
AD      |3  |4  |JP         |1  |2
CN      |4  |4  |US         |3  |3

但查询需要很多时间。有什么方法可以加快速度吗?

1 个答案:

答案 0 :(得分:2)

问题是你对所有字段使用distinct,你没有(),这需要很长时间。尝试仅对一列使用distinct

像这样

    SELECT DISTINCT (a.localgeo), a.foreigngeo, b.lat, b.lng, c.lat, c.lng
    FROM tbl_correlateddata a 
    JOIN tbl_geodetail b 
      ON a.localgeo = b.code 
    JOIN tbl_geodetail c 
      ON a.foreigngeo = c.code

编辑:

     SELECT DISTINCT a,b,c FROM t

大致相当于:

     SELECT a,b,c FROM t GROUP BY a,b,c

所以你应该这样做

     SELECT a.localgeo, a.foreigngeo, b.lat, b.lng, c.lat, c.lng
    FROM tbl_correlateddata a 
    JOIN tbl_geodetail b 
      ON a.localgeo = b.code 
    JOIN tbl_geodetail c 
      ON a.foreigngeo = c.code
     GROUP BY a.localgeo ,a.foreigngeo