SQL and Coldfusion left join tables getting duplicate results as a list in one column

后端 未结 4 1201
醉酒成梦
醉酒成梦 2021-01-25 20:56

lets say I have two tables: Persons (P_Id, Name) and Orders (O_Id, OrderNo, P_Id)... I want to do a left join which would be:

SELECT Persons.Name, Orders.OrderNo         


        
4条回答
  •  耶瑟儿~
    2021-01-25 21:11

    What I really need to be able to get is one row for each person and all the OrderNo belonging to that person in a list.

    No, you don't, you really, really don't.


    You can do what you've already done, and loop through the results. When the first column changes value, you know you've moved on to a new person. One issue may be that you're returning the name again and again and again, once for each order id. In which case return two record sets, each in the same order...

    SELECT Persons.P_Id, Persons.Name
    FROM Persons
    ORDER BY Persons.Name
    
    SELECT Persons.P_Id, Orders.OrderNo
    FROM Persons
    INNER JOIN Orders
    ON Persons.P_Id=Orders.P_Id
    ORDER BY Persons.Name
    

    (You don't need a LEFT JOIN now, because you can infer a person with no orders as you loop through the two record sets.)

提交回复
热议问题