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

问题描述 投票:0回答:1

我有两个子查询,这些子查询生成了灯具列表和用户具有管理员特权的团队列表。

我可以为团队列表调用相同的(非常复杂的)子查询两次,就像这样:


(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 subquery alias
1个回答
0
投票

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

对于8.0之前的MySQL版本,不支持CTE的版本,无法多次引用相同的内联视图。

© www.soinside.com 2019 - 2024. All rights reserved.