3

I did multiple searches for an answer to this (on SO and elsewhere), but haven't found an answer that really fit my needs (if it's out there, I apologize in advance).

I have a query, using PHP, that returns an array from a database (WordPress). Basically what I want to do is look at a column's value, and then LIMIT based on that value. Here's the array that's returned for a better idea:

http://pastebin.com/AC043qfh

In the query, you'll notice that the value for post_parent repeats for several of returned arrays. What I want to do is have it LIMIT to 3 based on the post_parent value e.g. I want 3 entries for post_parent 79, 87, 100, etc.

I'm not well versed (see: at all) in MySQL queries, but this is what I have to get that array:

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)

I've tried using GROUP BY, but that didn't get me what I wanted. Any help is appreciated.

EDIT Just to clarify, these are the results I want: http://pastebin.com/pWXdUuXv

4

1 回答 1

3

这可能会奏效:(我假设 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
;

编辑:尝试在排名中包含类别,以便它真正起作用。

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

于 2013-09-13T16:45:05.240 回答