基于mysql中的最小id返回唯一行

时间:2015-04-01 13:26:54

标签: mysql sql

我坚持这一点:
我需要根据最小 ID 获取 guid ,并删除所有其他重复项(guid,ID)。 ID在这里只是唯一的字段。

+-----------------------------+------+-------------+
| guid                        | ID   | post_parent |
+-----------------------------+------+-------------+
| 5.jpg                       | 7626 |        2418 |
| 3.jpg                       | 7625 |        2418 |
| 2.jpg                       | 5972 |        2418 |
| 2.jpg                       | 3000 |        2420 |
| 0.jpg                       | 3205 |        2420 |
| 9.jpg                       | 9205 |        2419 |
+-----------------------------+------+-------------+

所以我想要的是:

+-----------------------------+------+-------------+
| guid                        | ID   | post_parent |
+-----------------------------+------+-------------+
| 2.jpg                       | 5972 |        2418 |
| 2.jpg                       | 3000 |        2420 |
| 9.jpg                       | 9205 |        2419 |
+-----------------------------+------+-------------+

当然,我可以使用这样的东西:

select guid,
       ID 
       from wp_posts where ID = ( 
        select MIN(ID) from wp_posts 
        where post_parent="2418");

但我需要从表中获取所有数据,而不是单行。

3 个答案:

答案 0 :(得分:2)

select * 
  from wp_posts p,
       (select min(ID) as id, post_parent
          from wp_posts 
      group by post_parent) mins
  where p.ID = mins.id and mins.post_parent = p.post_parent

答案 1 :(得分:1)

找到最小ID为

的行
SELECT *
FROM wp_posts p
WHERE NOT EXISTS (  SELECT 'a'
                    FROM wp_posts p2
                    WHERE p2.post_parent = p.post_parent 
                    AND p2.id < p.id
                  )

答案 2 :(得分:1)

select distinct z.guid, z.id, z.post_parent from (
    select distinct post_parent, min(id) pp 
    from wp_posts
    group by post_parent
) bb
inner join wp_posts z on z.post_parent = bb.post_parent and z.id = bb.pp