0

I want to ask best method to select two meta value from same column

my code

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 Answer 1

1

You just need to join postmeta twice:

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 );

Also note that I used $wpdb->prepare() in place of sprintf(). It's the preferred method for safely putting values into a query with WordPress.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.