MySQL從8.0版本開(kāi)始支持WITH語(yǔ)句,可以使得查詢(xún)更加簡(jiǎn)單、清晰、高效。
WITH cte AS ( SELECT column_1, column_2, column_3 FROM table_1 ) SELECT cte.column_1 as col_1, SUM(table_2.column_2) as sum_col2 FROM cte JOIN table_2 ON cte.column_2 = table_2.column_2 GROUP BY cte.column_1 ORDER BY sum_col2 DESC;
上面的查詢(xún)代碼中,WITH語(yǔ)句的名稱(chēng)為cte,查詢(xún)的結(jié)果集指定了三個(gè)列。接下來(lái)的SELECT語(yǔ)句中引用了cte,后面會(huì)和另外一個(gè)表進(jìn)行JOIN操作,最后對(duì)結(jié)果進(jìn)行了分組和排序。如果沒(méi)有使用WITH語(yǔ)句,可能需要在查詢(xún)中寫(xiě)多次相同的子查詢(xún),WITH語(yǔ)句可以讓查詢(xún)語(yǔ)句更加簡(jiǎn)潔易懂。
需要注意的一點(diǎn)是,WITH語(yǔ)句的查詢(xún)結(jié)果也可以被其他查詢(xún)使用。例如:
WITH cte AS ( SELECT column_1, column_2, column_3 FROM table_1 ) SELECT cte.column_1 as col_1, SUM(table_2.column_2) as sum_col2 FROM cte JOIN table_2 ON cte.column_2 = table_2.column_2 GROUP BY cte.column_1 HAVING sum_col2 >( SELECT AVG(sum_col2) FROM ( WITH cte_2 AS ( SELECT column_1, column_2, column_3 FROM table_1 ) SELECT cte_2.column_1 as col_1, SUM(table_2.column_2) as sum_col2 FROM cte_2 JOIN table_2 ON cte_2.column_2 = table_2.column_2 GROUP BY cte_2.column_1 ) as subquery ) ORDER BY sum_col2 DESC;
上面的代碼中,內(nèi)部的WITH語(yǔ)句cte_2也被用于了HAVING子句中的子查詢(xún)中。
總結(jié)來(lái)說(shuō),MySQL支持WITH語(yǔ)句可以讓查詢(xún)更加清晰、簡(jiǎn)潔、高效,特別是對(duì)于需要多次使用相同子查詢(xún)的場(chǎng)景。但是需要注意WITH語(yǔ)句的查詢(xún)結(jié)果也可以被其他查詢(xún)使用。