使用MySQL的WITH子句来定义子查询,然后在查询中引用它,以避免在SELECT部分中多次复制粘贴子查询。
示例代码:
WITH sales_by_month AS ( SELECT DATE_FORMAT(sales_date, '%Y-%m') AS month, SUM(total_sales) AS total FROM sales_table GROUP BY month ) SELECT products.product_name, products.product_price, sales_by_month.total FROM products INNER JOIN sales_table ON products.product_id = sales_table.product_id INNER JOIN sales_by_month ON DATE_FORMAT(sales_table.sales_date, '%Y-%m') = sales_by_month.month;