I'm trying to use GROUP_CONCAT with DISTINCT, but by executing the distinction on a different column. For example, I'm doing this:
GROUP_CONCAT(DISTINCT tags.tag SEPARATOR ' ') as tags"
But a tag could be the same characters with a different id, so I would need to do something like this:
GROUP_CONCAT(DISTINCT(tags.tag_id) tags.tag SEPARATOR ' ') as tags"
However I can't find anything about this, any ideas?
SIMPLIFIED table data examples (model and SQL request are a lot more complex with multiple joins and tables):
items table:
item_id , title , ...
1, Smith, ...
2, Bob, ...
...
tags table:
tag_id , tag , item_id , ...
1, Montreal, 1, ...
2, Toronto, 1, ...
3, Toronto, 1, ...
4, New-York, 2, ...
...
The MySQL query:
...
SELECT items.item_id, items.title,
GROUP_CONCAT(DISTINCT tags.tag_id SEPARATOR ',') as tag_ids",
GROUP_CONCAT(DISTINCT tags.tag SEPARATOR ' ') as tags"
LEFT JOIN tags ON items.item_id = tags.item_id
GROUP BY items.item_id
..
Expected result:
item1.title = "Smith"
item1.tag_ids = "1 2 3"
item1.tags = "Montreal Toronto Toronto"
...
Actual result:
item1.title = "Smith"
item1.tag_ids = "1 2 3"
item1.tags = "Montreal Toronto" <-- MISMATCH IN TAGS COUNT BECAUSE OF DISTINCT
...
NOTE: I would like to avoid sub-queries like
SELECT WHERE tags.item_id IN(SELECT ...)
I'm not 100% sure what you want but if I'm right, you want distinct tag_ids and then corresponding tag names, so 'montreal toronto toronto' would be fine for you:
SELECT item_id,
GROUP_CONCAT(tag_id SEPARATOR ' ') AS tag_ids,
GROUP_CONCAT(tag SEPARATOR ' ') AS tags
FROM
(SELECT items.item_id AS item_id,
tags.tag_id AS tag_id,
tags.tag AS tag
FROM items
JOIN tags ON tags.item_id = items.item_id
GROUP BY 1,
2) AS distinct_groups
GROUP BY item_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.