MySQL | LEFT JOIN wp_posts and wp_postmeta

I like to LEFT JOIN both tables, wp_posts and wp_postmeta. In my posts i have create several meta box options.

Lets say I have create a custom post type called “ads” and for each ad, i have the publication date and the expiration date as meta options.

Read More

the question is, how can I join the two tables, in order to get the ID of the post, from the wp_posts table where the current date is higher than the start date in the post meta table and lower than the expiration date in the post meta table.

for non WP users the wp_posts table is a traditional table, where each row represents a post and the wp_postmeta is a key value pare table where based on the post id, contains more than one row to describe the meta options of the post.

Is there a way to make that query in a single MySQL Query ?

kind regards.

Related posts

Leave a Reply

1 comment

  1. I take you to mean that “start date” is the “publication_date”.

    Absent a schema definition, I will guess at the column names and datatypes

    One way to get this would be to use correlated subqueries in EXISTS predicates, though this may not be the most efficient approach:

    SELECT p.id
      FROM wp_posts p
     WHERE EXISTS
           ( SELECT 1
               FROM wp_postmeta m1
              WHERE m1.wp_posts_id = p.id
                AND m1.meta_option_name = 'publication date'
                AND m1.meta_option_date_value <= NOW()
           )
       AND EXISTS
           ( SELECT 1
               FROM wp_postmeta m2
              WHERE m2.wp_posts_id = p.id
                AND m2.meta_option_name = 'expiration date'
                AND m2.meta_option_date_value > NOW()
           )
    

    You specifically asked about using a LEFT JOIN

    An equivalent result can be obtained using LEFT JOIN operations (although this query is really equivalent to doing INNER JOIN operations):

    SELECT p.id
      FROM wp_posts p
      LEFT
      JOIN wp_postmeta m1
        ON m1.wp_posts_id = p.id 
       AND m1.meta_option_name = 'publication date'
       AND m1.meta_option_date_value <= NOW()
      LEFT 
      JOIN wp_postmeta m2
        ON m2.wp_posts_id = p.id
       AND m2.meta_option_name = 'expiration date'
       AND m2.meta_option_date_value > NOW()
     WHERE m1.id IS NOT NULL
       AND m2.id IS NOT NULL
     GROUP 
        BY p.id