mysql合并两个查询

时间:2012-04-24 15:31:42

标签: mysql wordpress taxonomy

我正在尝试合并这两个查询,但我对mysql并不热衷。我怀疑我需要使用INNER JOIN或子查询?

我正在尝试将自定义分类法与插件合并。该插件要求我使用SQL访问我的Wordpress数据库。这是来自插件的查询:

SELECT p.*
FROM {$wpdb->prefix}most_popular mp
INNER JOIN {$wpdb->prefix}posts p ON mp.post_id = p.ID
WHERE
    p.post_type = '%s' AND
    p.post_status = 'publish'
{$order}
LIMIT %d

这是一个按我的分类法过滤掉内容的查询

SELECT SQL_CALC_FOUND_ROWS  wp_posts.* 
FROM wp_posts  
INNER JOIN wp_term_relationships 
ON (wp_posts.ID = wp_term_relationships.object_id) 
WHERE 1=1  
    AND ( wp_term_relationships.term_taxonomy_id IN (38) ) 
    AND wp_posts.post_type = 'post' 
    AND (wp_posts.post_status = 'publish') 
GROUP BY wp_posts.ID 
ORDER BY wp_posts.post_date 
DESC LIMIT 0, 10

我应该如何将所有这些合并到一个查询中?

1 个答案:

答案 0 :(得分:0)

SELECT p.*, wpt.*
FROM (SELECT * FROM {$wpdb->prefix}terms AS wpt1 WHERE wpt1.name='$loc' LIMIT 1) AS wpt
    , {$wpdb->prefix}most_popular AS mp
INNER JOIN {$wpdb->prefix}term_relationships wptr ON (mp.post_id = wptr.object_id) 
INNER JOIN {$wpdb->prefix}posts p ON mp.post_id = p.ID
WHERE 1=1
    AND ( wptr.term_taxonomy_id = wpt.term_id )
    AND p.post_type = '%s'
    AND p.post_status = 'publish'
{$order}
LIMIT %d

它可能很丑,但它确实有效。