decoded
decoded

Reputation: 25

mysql GROUP sorting

Please help me to sort mysql via php. My table look like following:

-----------------------------------------------------------
-title  |category       |sub_category |  content          
-----------------------------------------------------------
-ABC    |music          |album        |12345667
-----------------------------------------------------------
-Indie  |music          |null         |92384923
-----------------------------------------------------------
-rock   |music          |null         |02328232
-----------------------------------------------------------
-CAD    |music          |album        |somedata
-----------------------------------------------------------
-DDD    |music          |album        |somedata1
-----------------------------------------------------------
-folk   |music          |null          |92384923
----------------------------------------------------------

I want to result to retrieve like following

select * from table where category LIKE 'music' GROUP BY sub_category

I don't want to act null as group, so I should have result like following

-indie
-rock
-folk
-ABC(album)

in above results indie,rock,flok has null value in sub_category column and ABC is grouped

What is the correct mysql query to get such results? Is it possible?

Upvotes: 0

Views: 64

Answers (1)

GolezTrol
GolezTrol

Reputation: 116110

For the original wish:

 select * 
 from table 
 where category = 'music' 
 group by ifnull(sub_category, title)

For the new wish:

 select
   case when sub_category is null then
     title
   else
     concat(title, '(' , sub_category, ')')
   end as result
 from table 
 where category = 'music' 
 group by ifnull(sub_category, title)

This will give you just any title for album. It might be ABC or any other.

Upvotes: 0

Related Questions