gpt4 book ai didi

mysql - 需要一个查询逻辑,如何从 users 表中按 id 分组?

转载 作者:行者123 更新时间:2023-11-29 05:56:15 26 4
gpt4 key购买 nike

我有两个表:

INSERT INTO `companies` (`name`) VALUES
('Walmart'),
('Disney'),
('Amazon'),
('Unicom'),
('Microsoft'),
('Intel')

INSERT INTO `users` (`id`, `company`) VALUES
(1, 'Disney'),
(2, 'Amazon'),
(3, 'Intel'),
(3, 'Walmart'),
(4, 'Microsoft'),
(4, 'Unicom'),
(5, 'Microsoft')

结果应该如下:

1. 'Walmart', 'Amazon', 'Unicom', 'Microsoft', 'Intel'
2. 'Walmart', 'Disney', 'Unicom', 'Microsoft', 'Intel'
3. 'Disney', 'Amazon', 'Unicom', 'Microsoft'
4. 'Walmart', 'Disney', 'Amazon', 'Intel'
5. 'Walmart', 'Disney', 'Amazon', 'Unicom', 'Intel'

我试过:

"SELECT a.name, b.id, b.company FROM users RIGHT JOIN companies ON b.company <> a.name"

这通过省略已在列表中的公司名称给出了正确的逻辑,但问题是它处理相同的 id 两次并省略了不同的公司名称。如何处理这个查询?

最佳答案

下面查询的基本思想是将包含每个可能的用户/公司组合的日历表左连接到 users 表。那些确实匹配的组合被删除,然后使用 GROUP_CONCAT 将剩余的公司汇总到每个用户的 CSV 字符串中。

SELECT t1.id, GROUP_CONCAT(t1.name)
FROM
(
SELECT DISTINCT u.id, c.name
FROM users u
CROSS JOIN companies c
) t1
LEFT JOIN users t2
ON t1.name = t2.company AND t1.id = t2.id
WHERE t2.company IS NULL
GROUP BY
t1.id;

enter image description here

Demo

关于mysql - 需要一个查询逻辑,如何从 users 表中按 id 分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49124656/

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