我当前返回的行不止一个,因此我尝试使用此联接来联接最新的项目。

LEFT OUTER JOIN wp_posts wp_posts1 ON (wp_posts.ID = (SELECT MAX(post_parent) FROM wp_posts1 WHERE wp_posts1.post_parent = wp_posts.ID) )


但出现错误“ SQL错误:表'web13-a-tablename.wp_posts1'不存在”。

我下面的原始代码返回了太多结果。

SELECT
wp_posts.ID,
wp_posts.post_title,
wp_posts1.guid AS f_image,
wp_posts1.id AS f_ID
FROM wp_posts
LEFT OUTER JOIN wp_posts wp_posts1 ON (wp_posts.ID = wp_posts1.post_parent) AND wp_posts1.post_type = 'attachment'
WHERE wp_posts.post_type = 'custom'
AND wp_posts.post_status = 'publish'
AND (wp_posts.post_title LIKE '%smith%' OR wp_posts.post_title LIKE '%jones%')
ORDER BY
f_ID DESC


SQLFiddle显示选中的多行。我只想获得一行,并且想选择最大的f_ID。 http://sqlfiddle.com/#!2/97ee9/3/0

所需结果:

ID       POST_TITLE       F_IMAGE       F_ID
--------------------------------------------
2365     John Jones       IMG_URL       2490
2385     Becky Smith      IMG_URL       2390

最佳答案

将子查询更改为:

SELECT MAX(post_parent) FROM wp_posts as w3 WHERE w3.post_parent = wp_posts.ID


UPDATE将fiddle中的查询更改为:

SELECT
  wp_posts.ID,
  wp_posts.post_title,
  wp_posts1.guid AS f_image,
  MAX(wp_posts1.id) AS f_ID
FROM wp_posts
LEFT OUTER JOIN wp_posts wp_posts1 ON (wp_posts.ID = wp_posts1.post_parent) AND wp_posts1.post_type = 'attachment'
WHERE wp_posts.post_type = 'custom'
  AND wp_posts.post_status = 'publish'
  AND (wp_posts.post_title LIKE '%smith%')
GROUP BY
  wp_posts.ID

关于mysql - MYSQL-帮助仅加入1行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16787879/

10-13 04:48