首页 > 解决方案 > 在查询中为子选择添加条件

问题描述

我有这个查询

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 时,我如何才能获取行?

标签: databasepostgresqlpostgresql-9.4

解决方案


你可以使用group byandhaving子句。

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

推荐阅读