您的当前位置:首页正文

MySql数据库left join中添加子查询

2024-11-08 来源:个人技术集锦

user表查询出数据列表(多条,如id)左连接到order表中的order_agent_id字段,并通过 order_agent_id分组,求和user_order_partner,使用COALESCE()聚合函数对未获取到和值的进行默认赋值,防止查询不出数据不显示问题

SELECT COUNT(*)
FROM (
    SELECT 
        t.id,
        t1.create_time AS createTime,
        t.user_nickname,
        t.user_image AS userImg,
        t.user_tel,
        COALESCE(t1.total_price, '0.00') AS price
    FROM 
        db_user t
    LEFT JOIN (
        SELECT 
            order_agent_id, 
            create_time, 
            COALESCE(SUM(user_order_partner), '0.00') AS total_price
        FROM 
            db_user_order
        WHERE 
            order_status = 1 AND deleted = 0
        GROUP BY 
            order_agent_id, create_time
    ) AS t1 ON t.id = t1.order_agent_id
    WHERE 
        t.deleted = 0 AND (t.user_partner_id = ? AND t.user_level <> ?)
    ORDER BY 
        t1.total_price DESC
) AS TOTAL;

在实际应用中,需要替换占位符?为具体的值,并执行这个查询来获取结果。这个查询可能用于报告或分析目的,以了解有多少用户满足特定的订单和用户条件。

Top