【问题标题】:SQL reuse a subquery 'AS' as a parameter for another subquerySQL 重用子查询“AS”作为另一个子查询的参数
【发布时间】:2019-09-12 16:06:05
【问题描述】:

我是 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
[...]

提前致谢!

【问题讨论】:

  • 感谢@a_horse_with_no_name!是的,当然,这是 MySQL。我刚刚添加了一个标签。

标签: mysql sql subquery alias


【解决方案1】:

考虑将这些子查询迁移到派生表中(即在FROMJOIN 子句中查询,而不是SELECT 子句)。事实上,其中两个子查询可以变成整个表:invoices 和第二个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
[...]

【讨论】:

  • 哇!非常感谢@parfait!明天我会在工作中尝试,并会及时通知你。这很酷!
猜你喜欢
  • 2021-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多