gpt4 book ai didi

mysql - 具有多个表的复杂 MySQL 查询(阅读更多详细信息)

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

我有 4 个表:Teams、Users、UserTeams 和 Permissions:

用户:

UserID | Name
------------------------
1 | John
2 | Mike
3 | Tom

团队:

TeamID | Name
-------------------------------
1 | FC Barcelona
2 | Real Madrid
3 | Manchester United
4 | Liverpool

权限:

PermissionsID | Name
-------------------------------
1 | Read Comments
2 | Write Comments
3 | Send Email
4 | Admin

用户团队:

ID | UserID | TeamID | PermissionID
--------------------------------------------
1 | 1 | 1 | 1
2 | 1 | 1 | 2
3 | 1 | 1 | 4
4 | 1 | 2 | 1
4 | 1 | 4 | 3

-

-

UserID = 1(我们在查询之前就知道了)

我想查询得到这样的东西:

Permission.Name | FC Barcelona | Real Madrid | Manchester United | Liverpool | etc...
----------------------------------------------------------------------------
Read Comments | (something) | (something) | NULL | NULL
Write Comments | (something) | NULL | NULL | NULL
Send Email | NULL | NULL | NULL | (something)
Admin | (something) | NULL | NULL | NULL

队伍数量不限

有什么想法吗?我不介意是否有多个查询...

提前致谢!

解决方案

仅首先选择团队:

SELECT TeamID, name FROM Teams

然后使用 Teams 数据创建一个新查询:

SELECT     
Permissions.name as 'permissionName',

<Loop this line with the previous query>
MAX(CASE WHEN Teams.name = 'FC Barcelona' THEN Teams.name ELSE NULL END) AS 'FC Barcelona'
<End loop>

FROM Permissions
LEFT JOIN UserTeams ON UserTeams.PermissionID = Permissions.PermissionID AND UserTeams.UserID = '1'
LEFT JOIN Teams ON Teams.TeamID = UserTeams.TeamID
GROUP BY Permissions.name

现在我们得到了我们想要的结果。

最佳答案

好吧,我认为您的表格不完整..“(某物)”将存储在哪里

关于mysql - 具有多个表的复杂 MySQL 查询(阅读更多详细信息),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9116704/

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