且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-12-03 17:49:52

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

This might do the trick: (I'm assuming ID is unique, if not substitute something that is)

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
;

编辑:尝试将类别包括在排名中,以使其真正起作用.

Attempt to include category in rank so it'll actually work.

两次指定条件有点丑陋,但是我发现没有简单的方法可以解决这个问题.

Specifying conditions twice is a bit ugly, but I didn't see an easy way around it.