可以说我有两个表:Persons(P_Id,Name)和Orders(O_Id,OrderNo,P_Id)…我想做一个左联接,它是:
SELECT Persons.Name, Orders.OrderNo FROM Persons LEFT JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.Name
这将给我同一人的不同行号的多个行。我真正需要获得的是每个人一行,并且列表中属于该人的所有OrderNo。
使用Coldfusion,我可以查询Persons表,遍历每条记录,并针对每条记录对Orders进行查询,并获取该P_Id的结果并将其放在列表中,并将其作为新的“ OrdersList”添加到我的第一个查询中。但是我有成千上万的记录,这意味着要进行成千上万的查询!必须有更好的方法来做到这一点!
查找FOR XML-这样您就可以查看订单号。
FOR XML
看一下这个
With Person AS ( Select 1 PersonId, 'John' PersonName Union Select 2, 'Jane' ), Orders As ( Select 1 OrderId, 1 PersonId, Convert (DateTime, '1/1/2011') OrderDate Union Select 2, 1 , Convert (DateTime, '1/2/2011') Union Select 3, 1 , Convert (DateTime, '1/5/2011') Union Select 4, 1 , Convert (DateTime, '1/7/2011') Union Select 5, 1 , Convert (DateTime, '1/9/2011') Union Select 6, 2 , Convert (DateTime, '1/2/2011') Union Select 7, 2 , Convert (DateTime, '1/5/2011') Union Select 8, 2 , Convert (DateTime, '1/7/2011') ) Select PersonId, ( Select STUFF((SELECT ', ' + cast(O.OrderId as nvarchar) FROM Orders O Where 1=1 And O.PersonId = Person.PersonId FOR XML PATH('')), 1, 1, '') ) OrderList From Person
输出是
PersonId OrderList ----------- ----------------------- 1 1, 2, 3, 4, 5 2 6, 7, 8 (2 row(s) affected)