user1433150
user1433150

Reputation: 319

Can't figure out how to get result i want from query

I'm new to databases and mysql. I'm having a difficult time even deciding exactly what the problem I'm facing is and don't really know what the relevant google search would be. So forgive me if this is a mind-blowingly retarded question. I have two tables tabs and cats.

tabs is like this:

name | order
tab1 | 3
tab2 | 0
tab3 | 1
tab4 | 2

cats is like this:

name | tab_name
cat1 | tab3
cat2 | tab3
cat3 | tab1
cat4 | tab1
cat5 | tab1

I guess it's a one-to-many relationship tabs-to-cats. My question is how can I structure a query that will return only distinct tab names, each with all of its associated cats? I can get a result with all the cats and many duplicate tabs. Or I can get only distinct tabs but only one cat per tab. Maybe I should just be testing for duplicate tabs with my php code? Or querying tabs then querying all the cats for each tab? It just seems like there has got to be a more direct way. I'm currently using this query:

SELECT t.name AS tab, c.name AS cat FROM tabs t
LEFT JOIN categories c
ON t.name=c.tab_name
ORDER BY t.order;

Upvotes: 2

Views: 63

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173642

SQL ain't the best fit for hierarchical queries; however, your query output lends itself well for processing inside the application:

$tabs = array();
while ($row = $stmt->fetch()) {
    $tabs[$row['tab']][] = $row['cat'];
}

If you also need distinct categories:

    $tabs[$row['tab']][$row['cat']] = $row['cat'];

It generates a two-dimensional array with tabs as the first dimension and categories as the second.

Upvotes: 2

Michael Berkowski
Michael Berkowski

Reputation: 270677

You can use MySQL's GROUP_CONCAT() to produce a comma-separated list of cat, if that is what you want:

SELECT
  t.name AS tab,
  GROUP_CONCAT(c.name) AS cats
FROM 
  tabs t 
  LEFT JOIN categories c ON t.name = c.tab_name
GROUP BY tab
ORDER BY t.`order`   /* ORDER is a reserved keyword and has to be quoted as `order` */

This would produce output like:

tab      cats
------------------------------
Tab1     Cat1,Cat2,Cat3,Cat4
Tab2     Cat4,Cat3,Cat6,Cat7

However,

the query you have which produces multiple rows per tab is a more conventional way to handle this. In your application code, you would loop over the tab cat pairs and test for a change of the tab. If you use the GROUP_CONCAT() above, you would also need to split it on the , in your application code.

Either way, you cannot get a hierarchical result row-wise in the SQL - you have to repeat tab for each row. That's just the nature of the 2-dimensional structure of a result set. So it will require some application-side processing.

Upvotes: 3

Related Questions