mysql - SQL重用一个子查询 'AS'作为另一个子查询的参数

标签 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
[...]

提前致谢!

最佳答案

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

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

关于mysql - SQL重用一个子查询 'AS'作为另一个子查询的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57910673/

相关文章:

MySQL 5.5 和 5.6 默认值

mysql - JPQL 内连接

mysql - SQL如何根据另一列的值创建一个 boolean 列

java - 获取所有数据库并转换为字符串数组

sql - Laravel Eloquent检索第一个元素并保持查询结果完整吗?

mysql - sql - 选择包含 2 个表的一列

MySql select 语句有效但不能删除

include - 包括来自单独文件的 sparql 子查询

mysql - QueryDSL 和 Hibernate 未声明路径 'provider'/SQL 语法错误

MySQL 工作台 : Start Transaction seems to be committed before rollback