如果给定id有多个记录,则使用group by,having子句将告诉我。反正知道这两条记录在其余列中是如何相互不同的吗?
mysql>select pid, name, city from table1;
+------+-------------+--------+
| pid | name | city |
+------+-------------+--------+
| 1 | aa | delhi |
| 2 | bb | delhi |
| 3 | cc | mumbai |
| 4 | salman | pune |
| 4 | salman khan | pune |
+------+-------------+--------+
5 rows in set (0.00 sec)
mysql>select pid, count(*) as cnt from table1 group by pid having cnt > 1;
+------+-----+
| pid | cnt |
+------+-----+
| 4 | 2 |
+------+-----+
1 row in set (0.00 sec)
预期结果:
+------+-------------+
| pid | name |
+------+-------------+
| 4 | salman |
| 4 | salman khan |
+------+-------------+
2 rows in set (0.00 sec)
我可以通过使用以下查询来实现这一目标......
mysql>select pid, name from table1 where pid=4;
但我怎么知道这两行名称不同而且城市是一样的呢? 表中有一个时间戳列,我需要根据该时间对这些行进行排序。给定PID的Earlist记录将是第一个。
答案 0 :(得分:1)
要获得您发布的预期结果,请尝试:
select pid, name
from table1
where pid in
(select pid
from table1
group by pid
having count(*) > 1)
group by pid, name
如果您对
的情况特别感兴趣正如您在问题中解释的那样,请尝试:
select pid, name, city, timestamp
from table1
where pid in
(select pid
from table1
group by pid, city
having count(*) > 1)
group by pid, name, city
order by pid, city, timestamp
答案 1 :(得分:0)
通过Google搜索我发现Kodyaz.com中的以下示例可能会让您走上正确的轨道。