mysql从子查询中选择不起作用

时间:2017-02-03 15:38:02

标签: mysql

我想创建属于每个用户的订单总数和总收入的报告。

SELECT w.id, CONCAT_WS(' ', w.fname, w.sname) AS full_name, 
       te.total_earnings, te.assigned_jobs
FROM users AS w
LEFT JOIN (
    SELECT wr.user_id,
           COUNT(o.order_id) AS assigned_jobs,
           SUM(o.fee) AS total_earnings
    FROM (
        SELECT DISTINCT user_id, order_id, withdrawn
        FROM work_records
    ) AS wr
    LEFT JOIN orders o ON o.order_id = wr.order_id
    WHERE wr.withdrawn IS NULL
      AND o.verified != 'rejected'
) AS te ON te.user_id = w.id
WHERE w.status = 1


orders                      work_records
___________________      _________________________________
| order ID | fee  |      | id | order_id | fee | user_id |
-------------------      ---------------------------------
|   334    | 425  |      |  1 |   334    | 50  |    6    |
                         |  2 |   334    | 50  |    6    |

此查询适用于单个用户ID。但如果我想获得所有用户的报告,它就不起作用。

有任何建议吗?

1 个答案:

答案 0 :(得分:0)

以下是其他人的答案。但是查询的速度有多慢。但是如果你有更快的查询,那么就可以分享。

SELECT w.id, CONCAT_WS(' ', w.fname, w.sname) AS full_name, 
       te.total_earnings, te.assigned_jobs
FROM users AS w
LEFT JOIN (
    SELECT w.id,
        SUM(work.earnings) AS total_earnings,
        COUNT(work.order_id) AS assigned_jobs
    FROM users AS w
    LEFT JOIN (
        SELECT wr.order_id, wr.writer_id, o.fee AS earnings
        FROM work_records wr
        LEFT JOIN orders o ON o.order_id = wr.order_id
        WHERE wr.withdrawn IS NULL
          AND o.verified = 'verified'
        GROUP BY wr.order_id
    ) work ON work.writer_id = w.id
    GROUP BY work.writer_id
) te ON te.id = w.id