title: Export data from two MySQL tables into csv
body: <p>I'm having some kind of brain cramp here.</p>
  
  <p>I have two tables:</p>
  
  <p>MAIN:
  ID, Company Name, Address</p>
  
  <p>SEGMENT
  ID, Company_id, Segment (company_id links to ID in MAIN table)</p>
  
  <p>I want to export this into a csv. There are multiple segment rows associated with each Main row</p>
  
  <p>Ideally my export will look like</p>
  
  <pre><code>1, Ford, 123 Main Street, cars, trucks, vans
  2, Harley Davidson, 234 Elm Street, motorcycles
  3, John Deer, 345 Oak Street, tractors, riding mowers
  </code></pre>
  
  <p>In other words each row will have a variable number of fields</p>
  
  <p>I thought I could do something like</p>
  
  <pre><code>SELECT m.id, m.name, m.address, (select s.segment where m.id = s.company_id)
  FROM main m, segment s
  </code></pre>
  
  <p>but that's putting all segments on every row. I think I need an addition to the where clause in my nested select to specify 'for the current row' but I'm not sure how to do that.</p>
  
  <p>As is probably clear, I'm not very experienced with MySQL but sometimes the bus rolls over you even when you're not the right man for the job.</p>
  
  <p>Update: I should have been more clear. My struggle was getting the appropriate result set, not the actual exporting to csv (I use phpMyAdmin so can cheese that part). Adding a Group By phrase, as illustrated by Raphaël Althaus below, did the trick.</p>