1

I'm a little confused how to start this. I have a table of attribute names and then a table of attribute field names. As such

**Table: attributes**
id
name

**Table: attributes_fields **
id
attrID
fieldname

The attrFields can have multiple records attached to a single attr. I'm trying to get the output something like so.

Name    Fields (comma separated field id's)
9       1,3,4,5

So far I have this.

SELECT * 
FROM attributes 
    LEFT JOIN attributes_fields on attributes.attributeID = attributes_fields.attributeFieldParentID
WHERE attributes.attributeID = 9

Which works, but not as I would like it. I'm looking for one row to be returned. The above returns all the fields as multiple rows.

Any help would be great.

Thanks!

1
  • Show PHP code, please. Use mysqli , please. Commented Jan 29, 2015 at 19:40

2 Answers 2

1

You can use GROUP_CONCAT function to do this. This function returns a string result with the concatenated non-NULL values from a group. The full syntax is as follows:

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;

Or:

mysql> SELECT student_name,
    ->     GROUP_CONCAT(DISTINCT test_score
    ->               ORDER BY test_score DESC SEPARATOR ' ')
    ->     FROM student
    ->     GROUP BY student_name;

Please check it here: GROUP_CONCAT

Sign up to request clarification or add additional context in comments.

Comments

1

I was about to suggest GROUP_CONCAT as well. In your query:

SELECT a.id as Name, GROUP_CONCAT( f.id SEPARATOR ',') as Fields 
FROM attributes a
    LEFT JOIN attributes_fields f on a.attributeID = f.attributeFieldParentID
WHERE a.attributeID = 9

It should give you the result you're looking for.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.