mysql用主键选择最后一个重复记录

时间:2013-12-01 23:54:10

标签: php mysql csv greatest-n-per-group

我正在尝试创建一个查询语句,它通过列(Master)连接QueryPhoneNumber表,并仅检索复制的最后一条记录(如果存在) / p>

id      PhoneNumber     Flag    Date    
10009   425729233   N   2013-11-01
10011   425728397   N   2013-11-01
10012   425726253   Y   2013-11-01
10014   425726253   Y   2013-11-01

查询

PhoneNo
425729233
425728397
425726253
433699225

预期结果:

id      PhoneNumber     Flag    Date
10009   425729233   N   2013-11-01
10011   425728397   N   2013-11-01
10014   425726253   Y   2013-11-01

尝试过查询

Select id, PhoneNumber, Flag, Date from Master,Query where Master.PhoneNumber = Query.PhoneNo group by phoneNumber having max(id)

Select id,PhoneNumber, Flag, Date from Master, Query where Master.PhoneNumber = Query.PhoneNo and id in (select max(id) from Master)

有关如何从查询表中处理跳过的值433699225的任何帮助都会有所帮助。基本上,查询表是从csv导入的,它与主表和最终输出进行比较,包括匹配和不匹配的需要导出到csv中。

1 个答案:

答案 0 :(得分:0)

这是伎俩的小组,

Right Join用于从table2获取剩余的不匹配值。语法在哪里  对了

select Master.id, query.PhoneNo, Master.Flag, Master.Date from (select Master.id, Master.PhoneNumber, Master.Flag, Master.Date from Master where Master.id in (select max(id) from Master group by PhoneNumber)) Master right join query on Master.PhoneNumber = Query.PhoneNo

由于