如何在主查询中存储动态子查询的结果以进一步使用该值

时间:2016-09-15 11:31:57

标签: mysql sql database

我有一个长查询,有一些子查询。我想将子查询结果存储到变量中,因为我也想在下一个子查询中使用它们,这样我就不会给服务器加载。

我在这里举个例子,希望它描述我的情况。只关注// question starts from here//question ends here之间的部分。另一部分工作正常,但我迫切希望使用完整的SELECT子查询代替我用作别名的那些术语,或者我希望它们是变量。

SELECT a.field1, a.field2, b.field1, b.field2, c.field1,
(SELECT SUM(amount) FROM project_expense WHERE job_id=c.job_id
    GROUP BY c.invoice HAVING invoice<>'') AS p_expense,
(SELECT charges FROM ship_details WHERE some_condition=match) AS ship_exp,
(SELECT SUM(TIME_TO_SEC(---some time params---)/3600) FROM production_log
    WHERE job_id=c.job_id) AS p_hours,
(SELECT SUM(revenue) FROM exp_list WHERE job_id=c.job_id) AS p_revenue,

**
//question starts from here

(p_revenue/(p_expense*p_hours)+ship_exp) AS p_margin

//question ends here
**

FROM table_1 a
LEFT JOIN table_2 b
INNER JOIN table_3 c
WHERE c.date BETWEEN '2016-09-01' AND '2016-09-15'
ORDER BY b.company_name ASC

是否可以将每个子查询的结果存储到变量中? 所以我可以减轻查询的负担,这也是正确的方法。

感谢。

0 个答案:

没有答案