select中的SQL子查询可在一列中返回多个记录

时间:2019-10-26 01:30:39

标签: sql sql-server

像这样的示例,有没有办法让select子查询在单个列中返回多个记录?

Example


示例代码:

select u.fname,
       u.lname,
       (select item_id from products where user_id=u.user_id) as ITEM_IDS
from users u

1 个答案:

答案 0 :(得分:2)

这有效。

select u.fname,
       u.lname,
  STUFF(
    (SELECT ',' + CAST(item_id AS VARCHAR(20)) AS [text()]
     FROM products AS P
     where P.user_id=u.user_id
     FOR XML PATH('')), 1, 1, NULL) AS ITEM_IDS
from users u