gpt4 book ai didi

mysql - 在 MySQL 中两次加入相同的子查询

转载 作者:太空宇宙 更新时间:2023-11-03 11:22:31 27 4
gpt4 key购买 nike

我有两个子查询,它们生成一个固定装置列表,以及一个用户拥有管理员权限的团队列表。

我可以这样做,必须为团队列表调用相同(相当复杂)的子查询两次,如下所示:


(SELECT hometeam, awayteam etc... ) as fixtures

LEFT JOIN (SELECT team_id, admin etc... ) as teams1 ON fixtures.hometeam = teams1.team_id
LEFT JOIN (SELECT team_id, admin etc... ) as teams2 ON fixtures.awayteam = teams2.team_id

有没有一种方法可以使用团队列表查询的别名而无需执行两次?

最佳答案

MySQL 8.0 引入了对公用表表达式 (CTE) 的支持

请注意,这在早期版本的 MySQL 中不受支持,即在 5.7、5.6 中不可用

https://dev.mysql.com/doc/refman/8.0/en/with.html

像这样:

WITH
teams AS (SELECT team_id, admin etc... )
SELECT ...
FROM (SELECT hometeam, awayteam etc... ) AS fixtures
LEFT
JOIN teams t1
ON t1.team_id = fixtures.hometeam
LEFT
JOIN teams t2
ON t2.team_id = fixtures.awayteam
WHERE ...

MySQL 8.0之前的版本,不支持CTE的版本,无法多次引用同一个内联 View 。

关于mysql - 在 MySQL 中两次加入相同的子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58191026/

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