我有这样的多对多表格架构,
|------------| |--------------| |-----------|
| Products |-|-------<|ProductEngine |>---------|-| Engines |
| | | | | |
|------------| |--------------| |-----------|
在内部联接查询之后,我在下面得到了一个结果集:
SELECT product_id, engine_id
FROM Products
INNER JOIN ProductEngine
ON Products.product_id=ProductEngine.product_id
+---------------+--------------+
| product_id | engine_id |
+---------------+--------------+
| P001 | E001 |
| P001 | E002 |
| P002 | E003 |
| P002 | E004 |
| P002 | E005 |
+---------------+--------------+
如果我想获得这样的结果,如何编写SQL查询?
+---------------+----------------+
| product_id | engine_id |
+---------------+----------------+
| P001 | E001,E002 |
| P002 | E003,E004,E005 |
+---------------+----------------+
答案 0 :(得分:2)
他们是several techniques to converting row values into a string,我喜欢这个:
SELECT p1.product_id,
substring(
( SELECT ',' + engine_id
FROM ProductEngine p2
WHERE p2.product_id = p1.product_id
FOR XML PATH('') ), 2, 4000)
AS engine_id
FROM Products p1;
<强>被修改强>
现在正在按需要工作。 I have write an example to you