3

我有一个表 (Table D),它的字段与另一个表 (Table M) 相关联,其中包含一组引用 table 中单行的行D

可以(如果可以,如何)我可以创建一个 SQL 查询,它不仅可以从 中选择字段D,还可以与 table 连接M,在单个结果列中返回所有行值(仅来自一列),但全部连接在一起(最好有某种转义,这样它就不会被流氓数据污染M)?

编辑:

+-----------+----------+-------------+
| DataRowID | DataName | RandomField |
+-----------+----------+-------------+
| 1         | Foo      | Alice       |
+-----------+----------+-------------+
| 2         | Bar      | Bob         |
+-----------+----------+-------------+
| 3         | Baz      | Charlie     |
+-----------+----------+-------------+


+-----------+-----------+-----------+
| MetaRowID | DataRowID | MetaValue |
+-----------+-----------+-----------+
| 1         | 1         | Mercury   |
+-----------+-----------+-----------+
| 2         | 1         | Venus     |
+-----------+-----------+-----------+
| 3         | 1         | Earth     |
+-----------+-----------+-----------+
| 4         | 2         | Mars      |
+-----------+-----------+-----------+
| 5         | 2         | Jupiter   |
+-----------+-----------+-----------+
| 6         | 3         | Saturn    |
+-----------+-----------+-----------+
| 7         | 3         | Uranus    |
+-----------+-----------+-----------+
| 8         | 3         | Neptune   |
+-----------+-----------+-----------+
| 9         | 3         | Pluto     |
+-----------+-----------+-----------+

什么时候Where DataName = 'Bar'查询,

+-----------+----------+-------------+--------------+
| DataRowID | DataName | RandomField | MetaData     |
+-----------+----------+-------------+--------------+
| 2         | Bar      | Bob         | Mars,Jupiter |
+-----------+----------+-------------+--------------+
4

1 回答 1

2

使用MySql的GROUP_CONCAT功能:

SELECT d.ID, GROUP_CONCAT(m.Field) AS ConcatFields
FROM d JOIN m ON d.ID = m.dID
GROUP BY d.ID
于 2012-12-19T15:55:40.413 回答