dsa4d4789789 2018-05-29 08:33
浏览 91
已采纳

Codeigniter 2加入一对多查询3表

I have 3 tables

table1: documents (id, code, content)

table2: files (id, code, filename)

table3: tags (documentId, tag)

On my page, I have to display all the documents in a table view. like

code | content

123 | This is a sample document with file **files.filename** and tags **tags.tag**

Each document can have many files and tags

This is my current code.

return $this->db
    ->select('t1.id, t1.barcode, t1.sub, t1.source_type, t1.sender, t1.address, t1.description, t1.receipient, t1.status, t2.id as fileId, t3.tag as docTag')
    ->select('DATE_FORMAT(t1.datetime_added, \'%m/%d/%Y-%h:%i %p\') as datetime_added', FALSE)
    ->from('documents as t1')
    ->join('files as t2', 't2.barcode = t1.barcode', 'left')
    ->join('tags as t3', 't3.id = t1.id')
    ->order_by('id', 'desc')
    ->get()->result_array();
  • 写回答

2条回答 默认 最新

  • dqpfl2508589 2018-05-29 10:33
    关注

    You may use this query it will help you

    SELECT `doc`.`id`,
           (select GROUP_CONCAT(`tag`) from `tags` `tag` where `docid`=`doc`.`id` group by `docid`) as `tags`, 
          (select GROUP_CONCAT(`filename`)  from `files` where `docid`=`doc`.`id` group by `docid`) as `file`
    FROM `document` `doc` 
    

    if you have more files or tags for document it will show one record from document table,tags and file name will be comma separated if multi

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题