Self-joins on derived tables in mysql- do i need to repeat the subqueries?

Yar*_*rin 6 mysql sql

I've got to execute a self-joining sql statement on a derived table in mysql. The derived table involves a hairy subquery, and I'm wondering if there's any alternative to actually writing and executing it twice-

SELECT a.* FROM (my hairy subquery) AS a
  LEFT JOIN (my hairy subquery) AS a2 
    ON a.groupname = a2.groupname etc..
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 4

标准解决方案是使用 CTE,但 MySQL 尚不支持这些。替代方案是:

  • 您可以将子查询放入视图中并自连接视图。
  • 您可以创建一个临时表并用子查询的结果填充它。

有关的

  • @Yarin - 禁止任何特定于查询的优化,可能不会,因为您(可能)仍然执行视图两次(在 mySQL 中不起作用,抱歉)。如果“子查询”花费了大量时间,那么将其移动到临时表可能会(请注意,在那些支持 CTE 的系统中,如果您多次引用它,它们可以在幕后执行此操作)。 (2认同)