简体   繁体   中英

Ordering by using Group_Concat proving tricky

I'm somewhat new with php/mysql so I'm sure I'm missing something. This approach probably isn't the best either.

I have the following tables

Table: unit_members Fields: id, unit_id, person_id, primary

Table: persons Fields: id, name, rank_id

Table: ranks Fields: id, name, rank

Table: units Fields: id, name, rank

I'm trying to display each unit and the persons in each unit and have the persons sorted by rank which is an int field. It seems simple, but I'm unable to get the persons to be ordered by rank.rank.

Here's my query:

'SELECT unit_members.person_id, GROUP_CONCAT(persons.id) as personid, 
        GROUP_CONCAT(persons.name) as name, persons.rank_id, unit_members.unit_id, 
        units.id as unitid, units.name as unit, 
        GROUP_CONCAT(DISTINCT units.codename) as squad, ranks.id as rankid, 
        GROUP_CONCAT(ranks.rank) as rankrank 
FROM unit_members, ranks, persons, units
where persons.rank_id = ranks.id 
  and units.id = unit_members.unit_id 
  and persons.id = unit_members.person_id
group by units.codename
ORDER BY units.rank asc, ranks.rank asc';

It appears to me that the Order by here does not affect the Group_Concat, so my guess is I need to Order the Group_Concat somehow before it goes into an array. The array seems to order it by person id.

Any help would be greatly appreciated. Thanks in advance.

I think you just have some misconceptions.

Your ORDER BY isn't going to affect the results of GROUP_CONCAT() . You can change the order of results in a GROUP_CONCAT() function by specifying an order within the parens.

As it stands, your query is going to group by unit.codename, and within each unit.codename, the arbitrary results are going to be sorted first by units.rank, and then by ranks.rank.

A bigger problem: you keep talking about an array. There's no array here.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM