简体   繁体   中英

How do I concatenate the results from multiple join tables into a delimmited list using a single mySql query?

In MySql, I have a documents table, a folders table, and a searchtags table

Documents
  ID
  title

Folders
  ID
  title

Searchtags
  ID
  title

docFolders
  docID -> Documents.ID
  folderID -> Folders.ID

docSearchtags
  docID -> Documents.ID
  searchtagID -> Searchtags.ID

In the above, docFolders and docSearchtags are many-to-many join tables expressing the relationship between documents and folders, and documents and searchtags. A single document can have multiple folders and multiple searchtags associated with it.

I am wondering if it is possible to create a single query that will SELECT the title of all documents, as well as a delimmited list of every folder title that belongs to a each document, and also a delimmited list of every searchtag title that belongs to each document.

For example, the resultset might look something like this:

RESULT
docTitle                  | folderTitles           | searchtagTitles 
The Quick Brown Fox       | foxes, colours         | Bushy tails, browny, foxy
The Slow Green Turtle     | turtles, colours       | Hard shells, slimy, turtle-soup
The Cute Fluffy Bunny     | bunnies, cute          | Fluffy, rabbit, rabbit-stew

Thanks (in advance) for your help

Use:

  SELECT d.title AS doctitle,
         GROUP_CONCAT(DISTINCT f.title) AS foldertitles,
         GROUP_CONCAT(st.title) AS searchtagtitles
    FROM DOCUMENTS d
    JOIN DOCFOLDER df ON df.docid = d.id
    JOIN FOLDERS f ON f.id = dc.folderid
    JOIN DOCSEARCHTAGS dsc ON dsc.docid = d.id
    JOIN SEARCHTAGS st ON st.id = dsc.searchtagid
GROUP BY d.title

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM