向查询中的 sub select 添加条件

Add condition to sub select in query

我有这个问题

SELECT DISTINCT
    u.email,
    (
        SELECT
            count(DISTINCT o.id)
        FROM
            orders o
            INNER JOIN cart_dates cd ON cd.order_id = o.id
        WHERE
            u.id = o.user_id
    ) as count
FROM
    users u

如何仅在 count 小于 20 时获取行?

您可以使用 group byhaving 子句。

select u.email
from users u
inner join orders o on o.user_Id = u.id
inner join card_dates cd on cd.order_id = o.id
group by u.email
having count(distinct o.id) < 20