从两个不同的数据库表输出结果的最佳方法

时间:2014-07-02 16:35:34

标签: php mysql sql codeigniter

我的数据库announcementsannouncements_external中有两个表:

+----------+    +----------+
| table1   |    | table2   |
+----------+    +----------+
| id       |    | id       |
| catid    |    | eid      |
| uid      |    | username |
| title    |    | source   |
| text     |    | title    |
| views    |    | section  |
| images   |    | category |
| created  |    | text     |
| modified |    | views    |
| pubdate  |    | images   |
+----------+    | created  |
                | modified |
                +----------+

在CodeIgniter框架中,我想合并它们,所以当我执行foreach($results as $item)时,我会并排输出它们,按字段created排序。

我尝试了这段代码,但我知道合并完全错误了:

public function get_mixed( $limit = NULL, $offset = NULL )
{
    $this->db
        ->select('
            announcements.id,
            announcements.catid,
            announcements.uid,
            section.title AS section,
            categories.title AS category,
            announcements.title,
            announcements.text,
            announcements.views,
            announcements.created,
            announcements.modified,
            announcements.pubdate,
            announcements_external.id as eid,
            announcements_external.eid,
            announcements_external.source,
            announcements_external.username,
            announcements_external.section as esection,
            announcements_external.category as ecategory,
            announcements_external.title as etitle,
        ')
        ->join('categories', 'announcements.catid = categories.id', 'left')
        ->join('categories as section', 'categories.pid = section.id', 'left')
        ->join('announcements_external', 'announcements_external.id = announcements_external.id', 'right')
        ->order_by('created DESC, '.$this->_order_by);

    $query = $this->db->get( $this->_table_name, $limit, $offset )->result();

    return $query;
}

顺便说一下,我在LEFT JOIN表上categories,它可以正常工作,但我认为将它留在此代码中会更好,所以你也会看到它。

我可以获得更多信息的任何解决方案或指南吗?感谢

1 个答案:

答案 0 :(得分:1)

似乎Table1Table2是分开的实体,因此您需要使用UNION ALL而不是JOIN来合并它们。

(SELECT ..needed columns .. , Table1.created FROM Table1 JOIN categories ... )
UNION All
(SELECT ..needed columns .. , Table2.created FROM Table2 JOIN categories ... )
ORDER BY created ;

如有必要,您需要为非同义列使用假列别名。