我有一个SQL LIKE:
SELECT S.*,
(SELECT I.NAME FROM institution I, inst_map IM
WHERE IM.STUDENT = S.ID AND IM.INSTITUTION = I.ID) as INSTITUTIONS
FROM student S
在这种情况下,我的子查询可能会返回多个记录(我会收到错误:Subquery returns more than 1 row
)。
如何在逗号分隔的一个字段(在我的情况下为INSTITUTIONS
)中显示子查询中的多个值?
欢迎所有想法。
答案 0 :(得分:4)
尝试此查询 -
SELECT s.*, GROUP_CONCAT(t.NAME) INSTITUTIONS FROM student s
LEFT JOIN (SELECT * FROM institution i
JOIN inst_map im
ON im.INSTITUTION = i.ID
) t
ON s.ID = t.STUDENT
GROUP BY s.ID
GROUP_CONCAT函数将帮助您获取以逗号分隔的值。
答案 1 :(得分:0)
DECLARE @List VARCHAR(5000)
SELECT @List = COALESCE(@List + ', ' + Display, Display)
FROM TestTable
Order By Display
查询取自以下链接,文章完美地解释了查询,希望它有效 http://www.mitchelsellers.com/blogs/articletype/articleview/articleid/289/creating-comma-separated-list-in-sql.aspx
P.S它适用于SQL Server,我想