SQL语句思维不明显

时间:2013-02-21 18:25:10

标签: mysql sql

我想从一个表中检索所有行,其中一行中两列的所有值都与另一个roe中的其他两个值匹配,例如我将gps co-ords拆分为long和lat,我希望看到这些匹配在任何行???

2 个答案:

答案 0 :(得分:2)

简单的GROUP BY应该适合您:

SELECT Col1,Col2
FROM YourTable T
GROUP BY Col1,Col2
HAVING COUNT(*) > 1

请发布您尝试过的内容......

<强> - 编辑 -

如果您要查看返回所有具有相同纬度/经度的行,那么这样的行将起作用:

SELECT *
FROM YourTable
WHERE (lat,lon) IN (
      SELECT lat,lon
      FROM YourTable
      GROUP BY lat,lon
      HAVING COUNT(*) > 1
)

http://sqlfiddle.com/#!2/f9658/5

答案 1 :(得分:1)

你可以在where子句中有多个条件:

SELECT * FROM tbl1 
WHERE tbl1.lat = tbl2.lat AND tbl1.long = tbl2.long

对于你要求的同一张桌子,你可以尝试这样的自我加入:

SELECT t1.ID, t2.ID from myTable as t1
INNER JOIN myTable as t2
WHERE t1.lat = t2.lat and t1.long = t2.long

或者使用group来查看在返回的纬度/长度上使用子选择或第二个查询获得实际记录的数量和数量:

SELECT t.lat, t.lng, count(*) from myTable as t
GROUP BY (t.lat, t.long)
HAVING Count(*) >=2

使用子选择(可能需要调试):

SELECT * from myTable as t1, 
(SELECT t.lat, t.lng from myTable as t
GROUP BY (t.lat, t.long)
HAVING Count(*) >=2) as t2
WHERE t2.lat = t1.lat and t2.long = t1.long

如果有很多具有相同纬度/长度的记录,我建议使用具有2个或更多匹配条件的组来拉回纬度/长度,然后再次遍历表格以获得每个匹配的所有记录在代码中配对。