【发布时间】: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。我刚刚添加了一个标签。