duanmei1694 2015-03-03 19:46
浏览 373
已采纳

MySQL LEFT JOIN导致“重复”行

I have tables "customers" and "plans" and I want to list all customers regardless they have a plan or not. I'm using query to do it

SELECT customer.name, plan.goal
FROM customer
LEFT JOIN plan ON plan.customerid=customer.customerid
ORDER BY customer.name

I also want to see the goal (plan.goal) with the customer name. This works as long as customer does not have a plan or has a single plan. If customer has two or more plans then I get as many rows of customer name as there are plans.

What I want is customer.name and plan.goal from the latest plan. We can assume the higher value in plan.planid is the latest plan.

I guess I should use sub queries and INNER JOINS some how but I just don't get it right now...

  • 写回答

3条回答 默认 最新

  • dongpu3898 2015-03-03 19:54
    关注

    I would think something like this would work:

    SELECT customer.name, plan.goal
    FROM customer c
    inner join plan p on c.customerId = p.customerId
    inner JOIN (
        -- grabs the most recent plan per customer
        select max(planId) as planId, customerId
        from plan
        group by customerId
    ) maxPlan on p.planId = maxPlan.planId
    UNION
    -- handles customers w/o a plan
    select customer.name, null
    from customer c
    left join plan p on c.customerId = p.customerId
    where p.customerId is null
    ORDER BY customer.name
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大