从子查询中选择多个列

时间:2019-11-08 21:03:19

标签: mysql sql

希望一些SqL专家可以提供建议。我想从子选择中选择多个列。

这是一个工作示例。

SELECT
    customer.id as 'Customer ID'
    customer.name as 'Customer Name' ,
    (
        SELECT
            sum(bookings.commission)
        FROM
            bookings
        WHERE
            bookings.customer_id = c.id
    ) AS 'Customer Commission' ,
FROM
    customers AS c
WHERE
    c.status = 'active'

但是我想要更多的数据,即。

SELECT
    customer.id as 'Customer ID'
    customer.name as 'Customer Name' ,
    (
        SELECT
            sum(bookings.commission),
            sum(bookings.order_total)
        FROM
            bookings
        WHERE
            bookings.customer_id = c.id
    ) AS 'Customer Commission' ,
FROM
    customers AS c
WHERE
    c.status = 'active'

第二个示例中的通知订单总数。我知道我可以执行多个(SELECT ..),但我需要比示例中更多的分配,这会减慢速度。

希望您能提供建议。

1 个答案:

答案 0 :(得分:1)

使用LEFT JOINGROUP BY

SELECT c.id as customer_id, c.name as customer_name,
       b.commission, b.order_total
FROM customers c LEFT JOIN
     (SELECT b.customer_id, SUM(b.commission) as commission,
             SUM(b.order_total) as order_total
      FROM bookings b
      GROUP BY b.customer_id
     ) b
     ON b.customer_id = c.id
WHERE c.status = 'active'