找到至少有 1 个采购订单的最年轻的客户

Find the youngest customer with AT LEAST 1 purchase order

我需要编写一个查询来查找至少购买了 1 件产品的最年轻的顾客

这是数据: 客户:

ORDER_DETAIL:

到目前为止,这是我的查询:

SELECT c.CUSTOMERID, c.age, c.name
from (
SELECT CUSTOMERID, COUNT(ORDERID) as "totalOrder"
FROM FACEBOOK_ORDER_DETAIL
GROUP BY CUSTOMERID 
HAVING COUNT(ORDERID) >=1) AS tbl
LEFT JOIN FACEBOOK_CUSTOMER c on c.CUSTOMERID = tbl.CUSTOMERID
order by c.age ;

但是,上面的查询给了我

但我需要最低年龄的客户名单。

如果你真的只想要一个最小的顾客,即使有平局,那么使用 LIMIT:

SELECT c.CUSTOMERID, c.age, c.name
FROM CUSTOMER c
INNER JOIN FACEBOOK_ORDER_DETAIL o
    ON c.CUSTOMERID = c.CUSTOMERID
ORDER BY
    c.age
LIMIT 1;

这应该可行,因为如果客户加入订单详细信息 table,这意味着他至少有一个订单。

如果您想找到 所有 最年轻的客户,包括所有关系,那么处理此问题的好方法是使用 RANK 分析函数:

SELECT DISTINCT CUSTOMERID, age, name
FROM
(
    SELECT c.CUSTOMERID, c.age, c.name, RANK() OVER (ORDER BY c.age) rnk
    FROM CUSTOMER c
    INNER JOIN FACEBOOK_ORDER_DETAIL o
        ON c.CUSTOMERID = o.CUSTOMERID
) t
WHERE rnk = 1;

Demo

对于 MySQL 的早期版本,我们可以使用子查询作为没有 RANK:

的解决方法
SELECT DISTINCT c.CUSTOMERID, c.age, c.name
FROM CUSTOMER c
INNER JOIN FACEBOOK_ORDER_DETAIL o
    ON c.CUSTOMERID = c.CUSTOMERID
WHERE c.age = (SELECT MIN(t1.age)
               FROM CUSTOMER t1
               INNER JOIN FACEBOOK_ORDER_DETAIL t2
                   ON t1.CUSTOMERID = t2.CUSTOMERID);

Demo

您只需要 customers 中的列,所以我会这样表述:

select c.*
from (select c.*,
             rank() over (order by age) as seqnum
      from customers c
      where exists (select 1
                    from facebook_order_detail fod
                    where fod.customerid = c.customerid
                   )
    ) c
where seqnum = 1;

特别是,这不需要重复消除或聚合,所以它应该更快。它可以在 face_book_details(customerid) 上使用索引,也可能在 customers(age, customerid).

上使用索引