简体   繁体   中英

Single query MySQL collate hasAndBelongsToMany data

I have a set of tables

  • Documents
  • Groups
  • Keywords

Their are related as follows

  • Document has and belongs to many groups
  • Document has and belongs to many keywords

I want to create a query that selects all the documents, creating a different record for each group (because I will need to select by group) which also GROUP_CONCATs all the keywords into a single field.

The reason behind this is I am using sphinx to index the documents table and I need to it index title, content and keywords. I also have to be able to filter by group.

Here's what I have so far:

SELECT
    Link.document_id AS id,
    Link.group_id AS db_id,
    Document.title,
    Document.description,
    Group.name AS db_name,
    GROUP_CONCAT(distinct Keyword.`content` SEPARATOR ", ") as `keywords`
FROM `groups_documents` AS Link
    LEFT JOIN `documents` AS `Document` ON (Document.id = Link.document_id)
    LEFT JOIN `groups` AS `Group` ON (`Group`.id = Link.group_id)
    LEFT JOIN `keywords_documents` AS `KLink` ON (`KLink`.`document_id` = `Link`.`document_id`)
    LEFT JOIN `keywords` AS `Keyword` ON (`Keyword`.`id` = `KLink`.`keyword_id`)

but it doesn't work unfortunately, I only get one row.

If you use a group function in a statement containing no GROUP BY clause, it is equivalent to grouping on all rows.

You need add something as Group by Group . id

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