在MySQL中使用LIMIT来限制基于列值(PHP / MySQL)的结果


Using LIMIT in MySQL to limit results based on column value (PHP/MySQL)

我多次搜索了这个问题的答案(在SO和其他地方),但没有找到真正符合我需求的答案(如果它在那里,我提前道歉)。

我有一个使用PHP的查询,它从数据库(WordPress)返回一个数组。基本上,我想做的是查看列的值,然后基于该值进行LIMIT。下面是为了更好的主意而返回的数组:

http://pastebin.com/AC043qfh

在查询中,您会注意到 post_parent 的值对多个返回的数组重复。我想做的是根据post_parent值将其限制为 3,例如,我想要 3 个条目,分别表示 79、87、100 等post_parent。

我对 MySQL 查询并不精通(参见:根本没有),但这是我必须获得该数组的:

SELECT DISTINCT ID, guid, post_parent, post_title 
FROM $wpdb->posts p 
WHERE p.post_type = 'attachment'
    AND p.post_mime_type LIKE 'image/%'
    AND p.post_status = 'inherit'
    AND p.post_parent IN
        (SELECT object_id FROM $term_relationships WHERE term_taxonomy_id = $post_term)

我试过使用GROUP BY,但这并没有让我得到我想要的。任何帮助,不胜感激。

编辑 澄清一下,这些是我想要的结果:http://pastebin.com/pWXdUuXv

这可能会解决问题:(我假设 ID 是唯一的,如果不能替换它的话)

SELECT
  p.ID, guid, post_parent, post_title
FROM (
SELECT
  a.ID as ID,
  COUNT(*) as rank
FROM (
  SELECT ID, post_parent
  FROM $wpdb->posts
  WHERE post_type = 'attachment'
    AND post_mime_type LIKE 'image/%'
    AND post_status = 'inherit'
  ) AS a
JOIN (
  SELECT ID, post_parent
  FROM $wpdb->posts
  WHERE post_type = 'attachment'
    AND post_mime_type LIKE 'image/%'
    AND post_status = 'inherit'
  ) AS b ON b.ID <= a.ID AND b.post_parent = a.post_parent
GROUP BY a.ID
) AS r
JOIN $wpdb->posts p ON r.ID = p.ID AND r.rank <= 3
WHERE p.post_parent IN (
  SELECT object_id FROM $term_relationships
  WHERE term_taxonomy_id = $post_term)
GROUP BY p.ID
;

编辑:尝试在排名中包含类别,以便它实际工作。

两次指定条件有点丑陋,但我没有看到一个简单的解决方法。