从同一WordPress数据库中的表中获取所有相关数据

时间:2018-08-24 04:10:46

标签: php mysql sql wordpress object

我在DB WordPress中安装了2个自定义表,两个表之间具有NULL关系。

这是两个表:

one-to-many

如您所见,每个帖子都有一个类别,同时使用 posts table _________________________________________________________________ | id | title | content | category_id | post_order | post_active | |____|_______|_________|_____________|_____________|_____________| | 1 | test1 | testing | 1 | 0 | 1 | | 2 | test2 | testing | 1 | 1 | 1 | | 3 | test3 | testing | 2 | 2 | 0 | | . | ..... | ....... | . | . | . | |____|_______|_________|_____________|_____________|_____________| categories table _____________________________________ | c_id | c_name | c_order | c_active | |______|________|_________|__________| | 1 | cat1 | 0 | 1 | | 2 | cat2 | 1 | 1 | | 3 | cat3 | 2 | 0 | | . | ..... | ....... | . | |______|________|_________|__________| 表的category_id列和posts表的c_id列。

我想显示categories表中具有相关类别的所有数据。

这就是我尝试过的:

posts

但是我只在每个活动的global $wpdb; $results = $wpdb->get_results("SELECT b.c_name, a.id, TRIM(a.title) AS title, a.content FROM posts a INNER JOIN categories b ON a.category_id = b.c_id WHERE a.post_active = '1' AND b.c_active = '1' ORDER BY b.c_order, a.post_order", OBJECT_K ); print_r($results); 中获得第一篇帖子:

category

怎么了?如何解决?

1 个答案:

答案 0 :(得分:0)

尝试左联接,然后检查:

全局$ wpdb;

            $results = $wpdb->get_results("SELECT b.c_name, a.id, TRIM(a.title) AS title, a.content
            FROM posts a
            LEFT JOIN categories b ON a.category_id = b.c_id
            WHERE a.post_active = '1' AND b.c_active = '1'
            ORDER BY b.c_order, a.post_order", OBJECT_K );

            print_r($results);