Im trying to make it select the group with the highest display priority.
The problem is that it selects the group with the lowest ID and I’m not sure how to select the group with the highest display priority.
The SQL query looks like this:
SELECT xf_user_group_relation.user_id ,
xf_user_field_value.field_value,
xf_user_group_relation.user_group_id,
MAX( xf_user_group.display_style_priority ) AS display_style_priority
FROM xf_user_group_relation
INNER JOIN xf_user_group ON xf_user_group_relation.user_group_id = xf_user_group.user_group_id
INNER JOIN xf_user_field_value ON xf_user_group_relation.user_id = xf_user_field_value.user_id
WHERE xf_user_group.display_style_priority >= 500
AND field_id = 'minecraft'
AND xf_user_group_relation.user_group_id NOT IN(21,22)
GROUP BY xf_user_group_relation.user_id,
xf_user_field_value.field_value;
The groups are in xf_user_group with the structure:
user_group_id int(10) AUTO_INCREMENT
title varchar(50)
display_style_priority int(10)
user_css text
user_title varchar(100)
MySql errorneously lets you aggregate values without specifing ALL non-aggregates in GROUP BY. So it chooses on its own what value to show for user_group_id.
To get results you need, one would have to get maximum display_style_priority per user, and then join user_id and value back to original tables to filter them. There are two forms you might use, join:
And compare to maximum in a subqery:
Live demo is at Sql Fiddle.