Skip to content
Read For Learn
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP

Triple meta_key on custom SELECT query

Your Query is incorrect. To retrive meta values for triple meta_key you will need 3 different joins using posts meta on posts table.
Check code below:

// Example value
$user_id = 1;

// Calculate average post rating for user
$ratings_query = $wpdb->get_results(
                     $wpdb->prepare("
SELECT pmeta.meta_value  
    FROM wp_posts
      LEFT JOIN $wpdb->postmeta AS pmeta 
        ON (pmeta.post_id = $wpdb->posts.id) 
      LEFT JOIN $wpdb->postmeta AS pmeta1 
        ON (pmeta1.post_id = $wpdb->posts.id) 
      LEFT JOIN $wpdb->postmeta AS pmeta2 
        ON (pmeta2.post_id = $wpdb->posts.id) 
    WHERE $wpdb->posts.post_author = %d AND 
    $wpdb->posts.post_type="post" AND 
    $wpdb->posts.post_status="publish"
      AND (
        pmeta.meta_key = 'rating' 
        AND CAST(pmeta.meta_value AS CHAR) != '0'
      ) 
      AND (
        pmeta1.meta_key = 'anonymous' 
        AND CAST(pmeta1.meta_value AS CHAR) != 'true'
      ) 
      AND (
        pmeta2.meta_key = 'original_author' 
        AND CAST(pmeta2.meta_value AS CHAR) = ''
      )", $user_id), ARRAY_N);

To retrive meta data using custom query, you will need 1 joins for each meta data pairs on posts table as above.

if you print last SQL query using code echo $wpdb->last_query; , you will get SQL query:

SELECT 
  pmeta.meta_value 
FROM
  wp_posts 
  LEFT JOIN wp_postmeta AS pmeta 
    ON (pmeta.post_id = wp_posts.id) 
  LEFT JOIN wp_postmeta AS pmeta1 
    ON (pmeta1.post_id = wp_posts.id) 
  LEFT JOIN wp_postmeta AS pmeta2 
    ON (pmeta2.post_id = wp_posts.id) 
WHERE wp_posts.post_author = 1 
  AND wp_posts.post_type="post" 
  AND wp_posts.post_status="publish" 
  AND (
    pmeta.meta_key = 'rating' 
    AND CAST(pmeta.meta_value AS CHAR) != '0'
  ) 
  AND (
    pmeta1.meta_key = 'anonymous' 
    AND CAST(pmeta1.meta_value AS CHAR) != 'true'
  ) 
  AND (
    pmeta2.meta_key = 'original_author' 
    AND CAST(pmeta2.meta_value AS CHAR) = ''
  )

Related Posts:

  1. MySQL Query To Select Post By Postmeta
  2. Read post meta values, only if posts are public
  3. Lack of composite indexes for meta tables
  4. Safe to delete blank postmeta?
  5. How to get all term meta for a taxonomy – getting term_meta for taxonomy
  6. delete unused postmeta
  7. Short of raw SQL, can I query for multiple attachment metadata that have a given array key?
  8. Get updated post meta on save_post action?
  9. How to get the total number of meta_values based on a custom post type?
  10. Insert post metadata for all posts in CPT at once if metadata no existent
  11. MySQL Rank & $wpdb
  12. Set Condition echo function get_post_meta
  13. Get a row from a separate table by matching a posts meta_key to a tables ID column
  14. Compare string with post id in wpdb and do stuff when match is found
  15. Which is faster wpdb & get_row or wp_query & ge_post_meta?
  16. How to test the outcome of a wpdb query?
  17. How to delete duplicate records in wp_postmeta database table?
  18. wpdb->get_var – count author posts, meta value
  19. How to query and update one colum in postmeta table?
  20. Display current ranking of post as a number in post title
  21. get specific values from WordPress meta_value
  22. Database SQL query error
  23. Get data from custom table and update relative post_meta based on meta_key
  24. “BS_” rows in postmeta table
  25. How to search usermeta table
  26. why is my postmeta table is so heavy
  27. Get table parameter and save in meta value
  28. Display multiple meta_key/meta_values by single SQL query
  29. Exclude category from DB query
  30. Fetching array of postmeta with $wpdb and in_array conditional
  31. Which query method to use? (edit- wpdb syntax problems)
  32. Using mysql queries to delete custom post types based on meta_value
  33. Cache metadata for set of posts
  34. Export posts with postmeta without ID?
  35. How to get all the related ids without array?
  36. MySQL SELECT increment counter
  37. MySQL “Or” Condition
  38. MySQL – UPDATE query based on SELECT Query
  39. Create a temporary table in a SELECT statement without a separate CREATE TABLE
  40. MySQL Select Multiple VALUES
  41. MySQL error: Unknown column in ‘where clause’
  42. How do I retrieve the slug of the current page?
  43. Using wpdb to connect to a separate database
  44. How do you properly prepare a %LIKE% SQL statement?
  45. Most efficient way to get posts with postmeta
  46. Get posts by meta value
  47. Should I use wpdb prepare?
  48. Explanation of update_post_(meta/term)_cache
  49. How to extract data from a post meta serialized array?
  50. How to return number of found rows from SELECT query
  51. How to save an array with one metakey in postmeta?
  52. WordPress is stripping escape backslashes from JSON strings in post_meta
  53. How can I get the post ID from a WP_Query loop?
  54. Why are simple updates to wp_postmeta’s “_edit_lock” so slow?
  55. Check if Post Title exists, Insert post if doesn’t, Add Incremental # to Meta if does
  56. Return only Count from a wp_query request?
  57. Use REGEXP in WP_Query meta_query key
  58. How to fetch Data in WordPress using MySQLi or $wpdb
  59. How to update_post_meta value as array
  60. Adding meta tag without plugin
  61. What’s the point of get_post_meta’s $single param?
  62. What is the different between an attachment in wp_posts and an attachment in wp_postmeta?
  63. wpdb->insert multiple record at once
  64. How to edit a post meta data in a Gutenberg Block?
  65. Can i use php sql functions instead of $wpdb?
  66. Sanitizing integer input for update_post_meta
  67. post formats – how to switch meta boxes when changing format?
  68. Execute action after post is saved with all related post_meta records (data)
  69. How to define composite keys with dbDelta()
  70. Get a single post by a unique meta value
  71. How to correctly submit a search form and display the result in an independent page
  72. if get_post_meta is empty do something
  73. How we get_post_meta without post id
  74. How get post id from meta value
  75. What is the code to get the download link for a product in WooCommerce?
  76. So much data in postmeta
  77. advanced custom fields update_field for field type: Taxonomy
  78. $wpdb and MySQL Create Trigger
  79. update_post_meta not saving when value is zero
  80. find a random blogid across my multisite network that has at least one post published
  81. Content hooks vs User hooks
  82. $wpdb->delete column values IN ARRAY()?
  83. Meta compare with date (stored as string) not working
  84. Trying to get custom post meta through Jetpack JSON API [closed]
  85. wpdb->prepare function remove single quote for %s in SQL statment
  86. How to update/insert custom field(post meta) data with wordpress REST API?
  87. What is the advantage of the wp_options design pattern?
  88. Restrict post edit/delete based on user ID and custom field
  89. Custom query to get post names beginning with a digit
  90. Multipart/formatted MySQL query problem
  91. get_post_meta returning empty string when data shows in the database
  92. publish_post action hook doesn’t give post_meta_data
  93. Remove WordPress.org Meta link
  94. Remove post meta keys
  95. Alternative to mysql_real_escape_string
  96. How to access the post meta of a post that has just been published?
  97. Why time functions show invalid time zone when using ‘c’ time format?
  98. Increment value (value = value+1) of $wpdb->update
  99. Why is get_post_meta returning an array when I specify it as single?
  100. How to update/delete array in post meta value?
Categories post-meta Tags mysql, post-meta, select, wpdb
How to add post_author column to custom post type
WP API Get post with tag names instead of tag ID’s

Recommended Hostings

Cloudways: Realize Your Website's Potential With Flexible & Affordable Hosting. 24/7/365 Support, Managed Security, Automated Backups, and 24/7 Real-time Monitoring.

FastComet: Fast SSD Hosting, Free Migration, Hack-Free Security, 24/7 Super Fast Support, 45 Day Money Back Guarantee.

Recent Added Topics

  • Bug in translation system: load_theme_textdomain() returns true, files are available and accessible but the language defaults to english
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • Get the name of the template/*html file used
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
  • How to display the description of a custom post type in the dashboard?
  • Critical error on image display
  • Copying WP data and files into new install?
  • How to determine the DirectAdmin WordPress backup date?
  • How to get list of ALL tables in the database?
© 2026 Read For Learn
  • Database
    • Oracle
    • SQL
  • algorithm
  • asp.net
  • assembly
  • binary
  • c#
  • Git
  • hex
  • HTML
  • iOS
  • language angnostic
  • math
  • matlab
  • Tips & Trick
  • Tools
  • windows
  • C
  • C++
  • Java
  • javascript
  • Python
  • R
  • Java Script
  • jQuery
  • PHP
  • WordPress