[resolved] Confusion over relationship of wp_post and wp_postmeta tables (5 posts)

  1. kc11
    Posted 5 years ago #

    Hello all,

    I am confused over the relationship of the wp_posts and wp_postmeta tables.

    I would like to select all the posts from wp_posts, which do not have a custom field ( which I have created ) in the wp_postmeta table. I had been assuming that 'ID' in wp_posts is the primary key and that 'post_id' in wp_postmeta corresponds to it, but I'm no longer sure that this is the case.

    If this is not the case , then how does one link the 2 tables?

    I have been experimenting with the following query:

    $postIDs =  $wpdb->get_col("SELECT ID FROM $wpdb->posts INNER JOIN $wpdb->postmeta ON  ID=post_id WHERE meta_key<>'keyword'");

    this returns the correct post_ids from the wp_postmeta table.

    However I am looking for The IDs from the wp_posts table.

    Any ideas on how to write a query to get the latter?

    Thanks in advance,


  2. popper
    Posted 5 years ago #

    You are getting the ids from the post table, just once for every meta value corresponding to that ID in the wp_postmeta table, if you just want to get the id once, you could group them

    SELECT ID from wp_posts inner join wp_postmeta on (id = post_id) HERE meta_key<>'keyword' group by id

    or maybe do something different like

    SELECT ID from wp_posts where not exists ( SELECT * from wp_postmeta where (post_id =ID) and (meta_key='keyword'));

  3. kc11
    Posted 5 years ago #

    Thank you. That worked!



  4. Mark / t31os

    Posted 5 years ago #

    Adding this in as a point of reference on previous discussion on grabbing posts "without" given post meta.


  5. kc11
    Posted 5 years ago #

    Thanks Mark


Topic Closed

This topic has been closed to new replies.

About this Topic


No tags yet.