【问题标题】:Codeigniter: Selecting different columns from 3 tablesCodeigniter:从 3 个表中选择不同的列
【发布时间】:2016-05-22 10:07:50
【问题描述】:

今天我在开发我的应用程序时遇到了问题。 我重组了我的数据库。

我有 3 个表格用于帖子、照片和帖子的标签。

我加入了另外两个表(照片、标签)。

我想查询前 3 个帖子,其中只有一个带有照片和标签的 SELECT,但结果中只显示第一行。

这是我的代码:

$this->db->select('owner, title, time, LEFT(content, 75) as content, category, url, price, county');

$this->db->from(POSTS_TABLE);

$this->db->join(PHOTOS_TABLE, PHOTOS_TABLE.'.post_id = '.POSTS_TABLE.'.url');

$this->db->join(TAGS_TABLE, TAGS_TABLE.'.post_url = '.POSTS_TABLE.'.url');

$this->db->order_by('time', 'desc');

$this->db->limit(3);

$query = $this->db->get();

$posts = $query->result();

我的数据库结构:

帖子表:

id, owner, title, content, url

tags 表:id、post_id(与 posts 表中的 url 列相同)、photo(指向照片的链接)

标签表:

 id, post_url (same as the url column from the posts table), tag.

请帮忙。我怎样才能只用一个 SELECT 并显示正确的结果来实现这一点?

我不能使用 WHERE 子句,因为我不知道确切的 post_url

【问题讨论】:

    标签: codeigniter mysqli


    【解决方案1】:

    考虑到列名'url'是行的id

    试试:

    // Code before
    $this->db->join('PHOTOS_TABLE', 'PHOTOS_TABLE.post_id = POSTS_TABLE.url');
    $this->db->join('TAGS_TABLE', 'TAGS_TABLE.post_url = POSTS_TABLE.url');
    // Code After
    

    【讨论】:

    • "考虑到列名'url'是行的id"不是真的,url是posts表中帖子的唯一id。可以有多行具有相同的'url'列在照片和标签表中。
    猜你喜欢
    • 2012-03-12
    • 2020-02-22
    • 2019-05-02
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    • 2016-05-14
    相关资源
    最近更新 更多