Question

Joomla has three tables:

user:

id | username
-------------
1  | you
2  | me

group:

id | title
-------------
1  | users
2  | managers

usergroups_map:

user_id | group_id
------------------
1       | 2
2       | 1
2       | 2

What I wanting to do is create a query (from which I will create a view) that flattens to look like:

user_id | username | users | manager
------------------------------------
1       | you      | 0     | 1
2       | me       | 1     | 1

So far I have something like this:

SELECT u.id, username, group_id, user_id, title
FROM joomla_users u
  LEFT JOIN joomla_user_usergroup_map map ON map.user_id = u.id
  LEFT JOIN joomla_usergroups g ON g.id = map.group_id
WHERE title = 'Super Users'

Which gives me one record for each group membership, but I really want to "flatten" it by turning each group name into a field which has a value of 0 or 1 depending on whether there is a record for that user in the usergroups_map.

Make any sense?

Was it helpful?

Solution

If the groups are fixed (users, managers) you can use something like this:

SELECT
  u.id,
  u.username,
  count(case when um.group_id = 1 then 1 end) users,
  count(case when um.group_id = 2 then 1 end) manager
FROM
  user u INNER JOIN usergroups_map um
  ON u.id = um.user_id
GROUP BY
  u.id, u.username

otherwise you need do use a solution like this:

SET @sql = NULL;
SELECT GROUP_CONCAT(CONCAT('count(case when um.group_id=',id,' then 1 end) ', title))
FROM `group`
INTO @sql;

SET @sql = CONCAT('SELECT u.id, u.username, ', @sql, ' FROM
  user u INNER JOIN usergroups_map um
  ON u.id = um.user_id
GROUP BY
  u.id, u.username');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Please see fiddle here.

If you need to create a view, just modify the above code with this:

SET @sql = NULL;
SELECT GROUP_CONCAT(CONCAT('count(case when um.group_id=',id,' then 1 end) ', title))
FROM `group`
INTO @sql;

SET @sql = CONCAT('CREATE VIEW yourview AS SELECT u.id, u.username, ', @sql, ' FROM
  user u INNER JOIN usergroups_map um
  ON u.id = um.user_id
GROUP BY
  u.id, u.username');

DROP VIEW IF EXISTS yourview;

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top