gpt4 book ai didi

MySQL 在与输出列不同的列上使用 GROUP_CONTACT 中的 DISTINCT

转载 作者:行者123 更新时间:2023-11-29 03:22:25 25 4
gpt4 key购买 nike

我正在尝试将 GROUP_CONCAT 与 DISTINCT 一起使用,但通过在不同的列上执行区分。例如,我正在这样做:

GROUP_CONCAT(DISTINCT tags.tag SEPARATOR ' ') as tags"

但是标签可以是相同的字符但不同的 id,所以我需要做这样的事情:

GROUP_CONCAT(DISTINCT(tags.tag_id) tags.tag SEPARATOR ' ') as tags"

但是我找不到任何相关信息,有什么想法吗?

SIMPLIFIED 表数据示例(模型和 SQL 请求对于多个连接和表要复杂得多):
项目表:
item_id, title, ...
1、史密斯……
2、鲍勃……
...

标签表:
tag_id, tag, item_id, ...
1, 蒙特利尔, 1, ...
2, 多伦多, 1, ...
3, 多伦多, 1, ...
4, 纽约, 2, ...
...

MySQL 查询:

...
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
..

预期结果:
item1.title = "史密斯"
item1.tag_ids = "1 2 3"
item1.tags = "蒙特利尔多伦多多伦多"
...

实际结果:
item1.title = "史密斯"
item1.tag_ids = "1 2 3"
item1.tags = "Montreal Toronto"<-- 由于不同而导致标签计数不匹配
...

注意:我想避免像

这样的子查询
SELECT WHERE tags.item_id IN(SELECT ...)

最佳答案

我不是 100% 确定您想要什么,但如果我是对的,您需要不同的 tag_id,然后是相应的标签名称,因此“montreal toronto toronto”适合您:

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

关于MySQL 在与输出列不同的列上使用 GROUP_CONTACT 中的 DISTINCT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41983518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com