将2个查询与不同行数组合在一起

时间:2016-01-23 13:46:52

标签: php mysql wordpress

我的查询连接到wordpress db并返回一些posts

为了获得每个帖子的image,我在php foreach loop

中运行了另一个查询

问题是在foreach loop内运行第二个查询非常慢,我需要另一种方法将这两个queries合并为1。

第一个查询

SELECT pm. * , p.*
FROM wp_posts p
JOIN wp_postmeta pm ON pm.post_id = p.ID
WHERE pm.meta_key = 'accommodation_location_post_id'
AND pm.meta_value
IN (   
SELECT pi.ID
FROM wp_posts pi
WHERE pi.post_title LIKE '%Cyprus%')

根据返回的帖子ID ,我需要每个ID 特色图片。

此查询执行此作业,但仅适用于 1 id

第二个查询

SELECT wp_posts.guid 
FROM wp_posts
WHERE wp_posts.ID = 
(Select wp_postmeta.meta_value 
FROM wp_postmeta 
WHERE wp_postmeta.meta_key = 
'_thumbnail_id' AND wp_postmeta.post_id = 'The id of each post')

我需要一个查询来返回所有帖子及其图片。

1 个答案:

答案 0 :(得分:2)

我真的不了解您的数据结构,但请尝试此查询

select
    t1.*, t2.guid
from (
    SELECT pm. * , p.*
    FROM wp_posts p
    JOIN wp_postmeta pm ON pm.post_id = p.ID
    WHERE pm.meta_key = 'accommodation_location_post_id'
AND pm.meta_value IN (
    SELECT pi.ID
        FROM wp_posts pi
        WHERE pi.post_title LIKE '%Cyprus%'
    )
) t1
left join (
    select
        p2.guid, pm2.post_id
    from
        wp_posts p2
        join wp_postmeta pm2 on
            pm2.meta_value = p2.ID
            and pm2.meta_key = '_thumbnail_id'
) t2 on t2.post_id = t1.ID