从元关键字和发布元关键字中选择两个值

时间:2017-09-14 作者:Diana Rider

我想问一下从同一列中选择两个元值的最佳方法

我的代码

global $wpdb, $bp;
            $user_id            =   get_current_user_id();
            $vlues=$wpdb->get_results(sprintf("
            SELECT rel.post_id as id, rel.meta_value as val
                FROM {$wpdb->posts} AS posts
                LEFT JOIN {$wpdb->postmeta} AS rel ON posts.ID = rel.post_id
                WHERE   posts.post_type   = \'books\'
                AND     posts.post_title LIKE \'%%fire\'
                AND     posts.post_status   = \'publish\'

                // Select specific book id
                AND     rel.meta_key   = \'books_id\'
                AND     rel.meta_value = \'1351\'

                // Check complete book
                AND     rel.meta_key   = %d
                AND     rel.meta_value > 0
                ", $user_id)
            );

1 个回复
最合适的回答,由SO网友:Jacob Peattie 整理而成

您只需加入两次Posteta:

global $wpdb, $bp;

$user_id = get_current_user_id();

$query = $wpdb->prepare(
    "SELECT 
        rel.post_id as id, 
        rel2.meta_value as val
    FROM {$wpdb->posts} AS posts
        LEFT JOIN {$wpdb->postmeta} AS rel ON 
            posts.ID = rel.post_id
        LEFT JOIN {$wpdb->postmeta} AS rel2 ON
            posts.ID = rel2.post_id
    WHERE
        posts.post_type = \'books\' AND
        posts.post_title LIKE \'%%fire\' AND
        posts.post_status = \'publish\' AND 
        rel.meta_key = \'books_id\' AND
        rel.meta_value = \'1351\' AND
        rel2.meta_key = %d AND
        rel2.meta_value > 0",
    $user_id
);

$values = $wpdb->get_results( $query );
还请注意,我使用了$wpdb->prepare() 代替sprintf(). 这是使用WordPress将值安全地放入查询的首选方法。

结束