gpt4 book ai didi

sql - 使用来自连接的逗号分隔列表更新数据库表字段

转载 作者:行者123 更新时间:2023-12-02 23:38:38 25 4
gpt4 key购买 nike

我有两个名为 DistrictsSchools 的表。 Districts 表包含一个名为 Schools 的列。

我需要从相应的 Schools 表中填充 Districts 表的 Schools 列,以便 中的每一行Districts 表有一个逗号分隔的列表,其中列出了 Schools 表中的学校名称值。

我该怎么做?我应该使用 UPDATE 查询还是存储过程?

我只得到了:

SQL Fiddle

地区表

+------------+------+---------+
| DistrictId | Name | Schools |
+------------+------+---------+
| 1 | a | |
| 2 | b | |
| 3 | c | |
| 4 | d | |
+------------+------+---------+

学校表

+----------+------------+------------+
| SchoolId | SchoolName | DistrictId |
+----------+------------+------------+
| 1 | s1 | 1 |
| 2 | s2 | 1 |
| 3 | s3 | 2 |
| 4 | s4 | 2 |
| 5 | s5 | 4 |
+----------+------------+------------+

输出需要如何

+------------+------+---------+
| DistrictId | Name | Schools |
+------------+------+---------+
| 1 | a | s1,s2 |
| 2 | b | s3,s4 |
| 3 | c | |
| 4 | d | s5 |
+------------+------+---------+

最佳答案

借助 FOR XML PATH STUFF 要连接这些值,您可以轻松地使用所需的结果更新表District

UPDATE  a
SET a.Schools = b.SchoolList
FROM Districts a
INNER JOIN
(
SELECT DistrictId,
STUFF((SELECT ', ' + SchoolName
FROM Schools
WHERE DistrictId = a.DistrictId
FOR XML PATH (''))
, 1, 1, '') AS SchoolList
FROM Districts AS a
GROUP BY DistrictId
) b ON A.DistrictId = b.DistrictId
WHERE b.SchoolList IS NOT NULL

关于sql - 使用来自连接的逗号分隔列表更新数据库表字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15524457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com