gpt4 book ai didi

mysql - SQL : Cartesian product + Join + Flatten

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

在 MYSQL 5.6 下,我有以下 2 个表:

CREATE TABLE User
(
id INTEGER,
login VARCHAR(32),
isservice BOOLEAN
);

CREATE TABLE Certificate
(
userid INTEGER,
serviceid INTEGER,
certificate VARCHAR(32)
);

具有以下数据:

用户:

id  |  login   |  isservice
---------------------------
1 | john | false
2 | bob | false
3 | serviceA | true
4 | serviceB | true

证书:(示例数据,证书列中的真实数据未知)

userid | serviceid | Certificale
---------------------------
1 | 3 | Alpha
1 | 4 | Bravo

我创建了以下 SQLFiddle:http://sqlfiddle.com/#!9/719a8/2

我正在搜索会给我以下内容的请求(不是存储过程):

id | login | certif_serviceA | certif_serviceB
-----------------------------------------------
1 | john | Alpha | Bravo
2 | bob | NULL | NULL

到目前为止,我已经尝试将我的请求基于:

SELECT  user.id, user.login,
service.login as serviceName
FROM User, User as service WHERE service.isservice=1 AND user.isservice=0

但我被困在那里:s

最佳答案

正如我已经评论过的,您绝对应该重新设计您的数据库。

您要的是 pivot table,使用 mysql 实现起来并不容易。你可以阅读here

但我为您提供了这种方法:

http://sqlfiddle.com/#!9/4dc0b2/1

SELECT  user.id, user.login,
GROUP_CONCAT(Services.login) as ServicesName,
GROUP_CONCAT(certificate.certificate) as Certificates
FROM User
LEFT JOIN Certificate
ON Certificate.userid = User.id
LEFT JOIN User Services
ON Certificate.serviceid = Services.id
WHERE NOT User.isservice
GROUP BY User.id

SELECT  user.id, user.login,
GROUP_CONCAT(CONCAT(Services.login,':',certificate.certificate)) as ServicesName
FROM User
LEFT JOIN Certificate
ON Certificate.userid = User.id
LEFT JOIN User Services
ON Certificate.serviceid = Services.id
WHERE NOT User.isservice
GROUP BY User.id

对于当前情况,您可能可以接受。

更新

SELECT  user.id, user.login,
GROUP_CONCAT(Services.login) as ServicesName,
GROUP_CONCAT(certificate.certificate) as Certificates
FROM User
LEFT JOIN User Services
ON Services.isservice
LEFT JOIN Certificate
ON Certificate.userid = User.id
AND Certificate.serviceid = Services.id
WHERE NOT User.isservice
GROUP BY User.id

http://sqlfiddle.com/#!9/1c062/4

关于mysql - SQL : Cartesian product + Join + Flatten,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33262705/

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