SQL重用子查询“ AS”作为另一个子查询的参数

时间:2019-09-12 16:06:05

标签: mysql sql subquery alias

我是SQL的新手,请尝试重用作为另一个子查询的参数创建的别名/子查询。

在一段时间内,我希望所有购买的客户都知道上次购买的日期,但是现在我试图将此日期传递给发票,以便获得关联的销售人员的姓名这张发票。

到目前为止,我有这个:

SELECT c.id,
       c.firstname,
       c.lastname,
       c.language,
       c.sex,
       c.company,
       c.city,
       c.postal_code,
       c.email,
       c.created_at,
       (SELECT max(`created_at`) FROM invoices WHERE client_id=c.id) AS last_purchase_date,
[...]
FROM 
    clients c
JOIN 
    boutiques b ON b.id = c.boutique_id
JOIN 
    brands br ON br.id = b.brand_id
[...]

,并且想要类似的东西:

SELECT c.id,
       c.firstname,
       c.lastname,
       c.language,
       c.sex,
       c.company,
       c.city,
       c.postal_code,
       c.email,
       c.created_at,
       u.name
       (SELECT max(`created_at`) FROM invoices WHERE client_id=c.id) AS last_purchase_date,
       (SELECT id FROM invoices WHERE created_at = last_purchase_date) AS last_invoice_id
       (SELECT name FROM users u WHERE id=last_invoice.user_id) AS sales_advisor
[...]
FROM 
    clients c
JOIN 
    boutiques b ON b.id = c.boutique_id
JOIN 
    users u ON u.boutique_id = b.id
JOIN 
    brands br ON br.id = b.brand_id
[...]

谢谢!

1 个答案:

答案 0 :(得分:2)

请考虑将这些子查询迁移到派生表中(即,使用FROMJOIN子句而不是SELECT子句中的查询)。实际上,这些子查询中的两个可以变成整个表:发票和第二个 users

SELECT c.id,
       c.firstname,
       c.lastname,
       c.language,
       c.sex,
       c.company,
       c.city,
       c.postal_code,
       c.email,
       c.created_at,
       u.name,
       agg.last_purchase_date,
       i.id AS last_invoice_id,
       u2.name AS sales_advisor
[...]
FROM 
    clients c
JOIN 
    boutiques b ON b.id = c.boutique_id
JOIN 
    users u ON u.boutique_id = b.id
JOIN 
    brands br ON br.id = b.brand_id
JOIN
    (
     SELECT client_id, max(`created_at`) as last_purchase_date
     FROM invoices
     GROUP BY client_id
    ) agg
  ON c.id = agg.client_id
JOIN 
    invoices i ON i.client_id = agg.client_id
               AND i.created_at = agg.last_purchase_date
JOIN 
    users u2 ON u2.id = i.user_id
[...]