获得订单超过2个但通过SQL登录不到3次的客户

时间:2014-03-27 09:11:51

标签: php mysql sql

我正在尝试让所有订单超过2个但只登录不到3次的客户。

我正在登录用户登录时。

但由于某些原因,我只返回错误数据的一行......

“user_log”表(user_id 19只登录过一次)

| user_log_id | date | user_id | type | module_id | unit_id |
|-------------|------|---------|------|-----------|---------|
|      1      |"date"|   19    |  1   |   NULL    |   NULL  |
|      2      |"date"|   20    |  1   |   NULL    |   NULL  |
|      3      |"date"|   20    |  1   |   NULL    |   NULL  |
|      4      |"date"|   20    |  1   |   NULL    |   NULL  |
|      5      |"date"|   20    |  1   |   NULL    |   NULL  |
|-------------|------|---------|------|-----------|---------|

“订单”表,其中user_id 19有2个订单(删除了不必要的列)

| order_id | user_id | status |
|----------|---------|--------|
|    10    |   19    |   1    | 
|    11    |   19    |   1    |
|    12    |   20    |   1    |
|    13    |   21    |   1    |
|    14    |   31    |   1    |
|----------|---------|--------|

我想要什么(User_id有2个订单,但已登录不到3次)

| user_id |
|---------|
|    19   |
|---------|

这就是我的SQL现在的样子。

$sql = "SELECT 
            ul.*, orders.order_id, orders.user_id, orders.firstname, orders.lastname, COUNT(ul.user_id) AS occourcence                
        FROM 
            orders
        LEFT JOIN
            user_log AS ul
        ON
            orders.user_id = ul.user_id
        WHERE 
            orders.status = 1
        AND
            ul.type = 1
        GROUP BY    
            orders.user_id
        HAVING
            COUNT(orders.user_id) > 1
        ORDER BY 
            orders.order_id DESC";

3 个答案:

答案 0 :(得分:1)

select user_id,count(user_log_id) from user_log
where user_id in
            (
                select user_id from Orderes
                            group by user_id
                            having count(order_id) =2
                    )
group by user_id
having count(user_log_id) < 3 

答案 1 :(得分:1)

避免任何子查询(并假设您已登录3次,并使2 或更多订单 - 与您的示例数据相匹配): -

SELECT a.user_id
FROM user_log a
INNER JOIN orders b
ON a.user_id = b.user_id
GROUP BY a.user_id
HAVING COUNT(DISTINCT user_log_id) < 3 AND COUNT(DISTINCT order_id) >= 2;

SQL小提琴: -

http://www.sqlfiddle.com/#!2/1b719/3

答案 2 :(得分:0)

试试这个

select o.user_id from
(
    select user_id from orders
    where status=1 
    group by user_id having count(*)>=2
) as o left join
(
    select user_id from user_logs
    where type=1
    group by user_id having count(*)<3
) as l
on o.user_id=l.user_id