我有点困惑如何开始这个。我有一个属性名称表,然后是一个属性字段名称表。因此
**Table: attributes**
id
name
**Table: attributes_fields **
id
attrID
fieldname
attrFields 可以有多个记录附加到一个 attr。我正在尝试获得类似这样的输出。
Name Fields (comma separated field id's)
9 1,3,4,5
到目前为止我有这个。
SELECT *
FROM attributes
LEFT JOIN attributes_fields on attributes.attributeID = attributes_fields.attributeFieldParentID
WHERE attributes.attributeID = 9
哪个有效,但不是我想要的那样。我正在寻找要返回的一行。以上将所有字段作为多行返回。
任何帮助都会很棒。
谢谢!
最佳答案
您可以使用 GROUP_CONCAT
函数来执行此操作。
此函数返回一个字符串结果,其中包含来自组的连接的非 NULL 值。完整语法如下:
GROUP_CONCAT([DISTINCT] expr [,expr ...]
[ORDER BY {unsigned_integer | col_name | expr}
[ASC | DESC] [,col_name ...]]
[SEPARATOR str_val])
mysql> SELECT student_name,
-> GROUP_CONCAT(test_score)
-> FROM student
-> GROUP BY student_name;
或者:
mysql> SELECT student_name,
-> GROUP_CONCAT(DISTINCT test_score
-> ORDER BY test_score DESC SEPARATOR ' ')
-> FROM student
-> GROUP BY student_name;
请在这里查看:GROUP_CONCAT
关于PHP MYSQL 返回字段中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28223128/