php - 如何单独交叉引用数据库表?

标签 php mysql wordpress

我一直在尝试找到一种方法(仅具备 php 的基本知识和极其乐观的决心)来搜索 wordpress 数据库中基于其他元值的元值。

我需要使用帖子的 ID 从一个表 (wp_posts) 中获取项目名称,使用它来获取另一个表 (wp_postmeta) 中具有相同名称的项目的 post_id,然后从同一个表中获取 a 的值获取的每个 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);
    ?>

由于第一个查询有效,后续的查询与我期望的一切都有效相比只是略有不同。但是,好吧,我错了。

顺便说一句,我已经尝试了许多语法变体,以防出现问题,并且我知道存在一些有关数组的问题。因此,任何建议将不胜感激。

最佳答案

使用别名:

SELECT 
    a1.Name, 
    b1.Info
FROM table2 b1
JOIN table2 a1 ON b1.id= a1.id AND a1.status = 1

关于php - 如何单独交叉引用数据库表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30761702/

相关文章:

css - 我可以在 CSS 伪类中使用 PHP

php - 允许在 WooCommerce 订单处于待处理状态时减少库存

php - 如果重复的 mysql 数据库如何插入或更新

PHP准备语句插入数据库

mysql - SQL查询以检查数据是否存在于特定数据数组中

mysql自动安装卡住了

mysql - 显示基于 current_user() mysql 的数据

php - 以编程方式添加/更新 woocommerce 产品的 SEO 元关键字

php - 我应该使用哪个 Paypal API 来支付您的员工?

php - yii2 中的 Css 和 bootstrap