codeigniter2连接一对多查询3表

lmyy7pcs  于 2021-06-23  发布在  Mysql
关注(0)|答案(2)|浏览(383)

我有三张table table1: documents (id, code, content) table2: files (id, code, filename) table3: tags (documentId, tag) 在我的页面上,我必须在表视图中显示所有文档。喜欢
code | content 123 | This is a sample document with file**files.filename**and tags**tags.tag** 每个文档可以有许多文件和标记
这是我现在的密码。

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();
nkcskrwz

nkcskrwz1#

更改此行: ->join('tags as t3', 't3.id = t1.id')

->join('tags as t3', 't3.documentid = t1.id') .

在按查询排序时还指定表:

->order_by('t1.id', 'desc').

希望有帮助?

abithluo

abithluo2#

你可以用这个查询它会帮助你

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`

如果文档有多个文件或标记,它将显示文档表中的一条记录,如果有多条记录,标记和文件名将用逗号分隔

相关问题