So, I've following columns: team_id, player_id, league_id, coach_id, venue_id in a posts table.Any given post can have bunch of id on each column.
Now, I want to order by DESC count of any id. For example:The result should be:
3 - league_id //because it has count total of 3
7 - team_id // because it as count total of 2
8 - player_id //because it has count of 2 and so on.
Basically, We order by count DESC but it has to be fro same column count.
Any way i can get it? It also has to give me column name so that i know the id from that column. Thank you!
A proper data model would have a separate junction/association table for each relationship:
post_teams
post_players
post_leagues
post_coaches
post_venues
Each of these would have properly declared foreign key relationships to the two referenced tables.
With such a model, your query would actually be pretty simple:
select which, id, count(*)
from ((select post_id, team_id as id, 'team' as which
from post_teams
) union all
(select post_id, players_id as id, 'players' as which
from post_players
) union all
(select post_id, leagues_id as id, 'leagues' as which
from post_leagues
) union all
(select post_id, coach_id as id, 'coach' as which
from post_coaches
) union all
(select post_id, venue_id as id, 'venue' as which
from post_venues
)
) x
group by which, id
order by count(*) desc;
I would advise you to fix your data model -- or switch to a database that has native support for arrays. MySQL has a great method for storing lists. It is called a table , not a string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.