1

Table ORDEM

ord_id | name
1      -  'A'
2      -  'B'
3      -  'C'
4      -  'D'

Table ORCAMENTO

orc_id | type
  10   -  'AA'
  20   -  'BB'
  30   -  'CC'
  40   -  'DD'

Table ORDEM_ORCAMENTO

id | ord_id | orc_id  
1  -   1    -   10
2  -   1    -   20
3  -   2    -   30
4  -   2    -   40

MySQL Query:

SELECT o.*, oo.orc_id 
FROM ordem AS o
        INNER JOIN ordem_orcamento AS oo ON oo.ord_id = o.ord_id
ORDER BY o.ord_id ASC

Results Got:

1 - 'A' - 10
1 - 'A' - 20
2 - 'B' - 30
2 - 'B' - 40 

Results Needed:

1 - 'A' - 10,20
2 - 'B' - 20,30

I want to put all id's from ORCAMENTO table that belongs to ORDEM table into an array...

I've tried many ways to figure it out but I haven't success...

1
  • Just return a result and process the array in PHP Commented Jul 23, 2014 at 18:42

2 Answers 2

3

GROUP_CONCAT allows you to select a group into a comma separated string

select o.ord_id, o.name, group_concat(oo.orc_id)
from ordem o
join ordem_orcamento oo on o.ord_id = oo.ord_id
group by o.ord_id, o.name
order by o.ord_id asc
Sign up to request clarification or add additional context in comments.

1 Comment

It's Perfect, I was using GROUP_CONCAT without 'group by' and didn't work fine, But now all is working perfect... Tks
0

You can build an array with php too, by looping the result

$data = array();
foreach ($result as $res) {
    $data[$res->ord_id][] = $res->orc_id
}

//output: foreach ($data as $orderitem) echo implode(",",$orderitem);

2 Comments

Could be, but I think about performance it wont work really well... Bringing clean results from the database still my best choice for performance...
yes of course. but if you need the seperate ids for some actions (counting etc), each time you have to explode the string.

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.