我一直试图找到一种方法(仅掌握基本的php知识和极其乐观的决心),在wordpress数据库中搜索基于其他元值的元值。
我需要使用post的ID从一个表(wp_posts)中获取项目名称,使用它来获取另一个表(wp_postmeta)中具有相同名称的项目的post_id,然后从同一个表中获取获得的每个post_id的特定自定义字段的值。
因为我是新手,所以我试图通过将其分解为部分来实现,而这就是我所拥有的。
<!-- This part works and gets the post title as expected -->
<?php
$result1 =$wpdb->get_results("SELECT post_title FROM $wpdb->posts , $wpdb->postmeta where $wpdb->posts.ID = $post->ID", OBJECT);
print_r($result1[0]->post_title);
?>
<!-- Then, I expected this to return the post_id of all entries where the title is the same as the one just obtained and where meta_key = custom_field_one. But it doesn't -->
<?php
$result2 =$wpdb->get_results("SELECT post_id FROM $wpdb->posts , $wpdb->postmeta where $wpdb->postmeta.meta_value = $result1 AND $wpdb->postmeta.meta_key = custom_field_one", OBJECT );
print_r($result2->post_id);
?>
<!-- So, unsurprisingly, this part doesn't work either. But it should use every post_id it just obtained to once again search the postmeta table -->
<?php
$result3 =$wpdb->get_results("SELECT meta_value FROM $wpdb->posts , $wpdb->postmeta where $wpdb->postmeta.post_id = $result2 AND $wpdb->postmeta.meta_key = custom_field_two", OBJECT );
print_r($result3->meta_value);
?>
由于第一个查询有效,后续的查询只是略有变化,我希望它能够正常工作。但是,我错了。
顺便说一句,我已经尝试了一些语法变体,以防出现问题,我发现有一些关于数组的问题。所以任何建议将不胜感激。
答案 0 :(得分:1)
使用别名:
SELECT
a1.Name,
b1.Info
FROM table2 b1
JOIN table2 a1 ON b1.id= a1.id AND a1.status = 1