返回带有多个元键的wpdb并按meta_value排序

时间:2012-04-18 23:26:50

标签: php sql wordpress sql-order-by wpdb

我正在尝试使用wordpress wpdb类返回自定义帖子,其中包含元键的两个值之一,然后按第三个元值对这些帖子进行排序。我可以得到我想要的帖子,但我似乎无法弄清楚如何按照我想要的方式对它们进行排序。

到目前为止我的功能是:

function artists_search_country($country_alt){
    global $wpdb;
    $querystr = "
        SELECT wposts.*
        FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
        WHERE wposts.ID = wpostmeta.post_id
        AND ((wpostmeta.meta_key = '_artist_country' AND wpostmeta.meta_value = '$country_alt')
        OR (wpostmeta.meta_key = '_artist_country_sub' AND wpostmeta.meta_value = '$country_alt'))
        AND wposts.post_type = 'artists'
        AND wposts.post_status = 'publish'
    ";
    $myposts = $wpdb->get_results($querystr, OBJECT);
    return $myposts;
}

我想做点什么:

function artists_search_country($country_alt){
    global $wpdb;
    $querystr = "
        SELECT wposts.*
        FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
        WHERE wposts.ID = wpostmeta.post_id
        AND ((wpostmeta.meta_key = '_artist_country' AND wpostmeta.meta_value = '$country_alt')
        OR (wpostmeta.meta_key = '_artist_country_sub' AND wpostmeta.meta_value = '$country_alt'))
        AND wposts.post_type = 'artists'
        AND wposts.post_status = 'publish'
        ORDER BY (wpostmeta.meta_key = '_artist_artist_last_name' AND wpostmeta.value) ASC
    ";
    $myposts = $wpdb->get_results($querystr, OBJECT);
    return $myposts;
}

请原谅ORDER BY行上的不良语法,但我不知道如何处理这一行,我尝试的所有内容都会破坏查询。任何帮助都会非常感激,因为我没有那么多的SQL查询经验。

1 个答案:

答案 0 :(得分:1)

试试这个SQL语句:

SELECT wposts.*, l.meta_value as artist_last_name
FROM $wpdb->posts wposts
    join $wpdb->postmeta wpostmeta
    on wposts.ID = wpostmeta.post_id
    join $wpdn->postmeta l
    on wposts.ID = l.post_id
    and l.meta_key = '_artist_artist_last_name'
WHERE
(( wpostmeta.meta_key = '_artist_country' AND wpostmeta.meta_value = '$country_alt')
OR (wpostmeta.meta_key = '_artist_country_sub' AND wpostmeta.meta_value = '$country_alt') )
AND wposts.post_type = 'artists'
AND wposts.post_status = 'publish'
ORDER BY l.meta_value ASC

您需要为艺术家的姓氏进行第二次加入。

另一个建议是利用Wordpress'$wpdb->prepare,如下所示:

$querystr = "
SELECT wposts.*, l.meta_value as artist_last_name
FROM $wpdb->posts wposts
    join $wpdb->postmeta wpostmeta
    on wposts.ID = wpostmeta.post_id
    join $wpdn->postmeta l
    on wposts.ID = l.post_id
    and l.meta_key = '_artist_artist_last_name'
WHERE
(( wpostmeta.meta_key = '_artist_country' AND wpostmeta.meta_value = %s)
OR (wpostmeta.meta_key = '_artist_country_sub' AND wpostmeta.meta_value = %s) )
AND wposts.post_type = 'artists'
AND wposts.post_status = 'publish'
ORDER BY l.meta_value ASC
";
$myposts = $wpdb->get_results($wpdb->prepare( $querystr, $country_alt, $country_alt ), OBJECT);

希望这有帮助。