MYSQL查询以压缩joomla组成员资格表

时间:2013-02-26 22:00:54

标签: mysql joomla flatten

Joomla有三张桌子:

用户:

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

组:

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

usergroups_map:

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

我想要做的是创建一个查询(我将从中创建一个视图),使其变平如下:

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

到目前为止,我有这样的事情:

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'

这为我提供了每个组成员资格的一条记录,但我真的想通过将每个组名称转换为值为0或1的字段来“扁平化”它,具体取决于该用户是否有该记录。 usergroups_map。

有道理吗?

1 个答案:

答案 0 :(得分:1)

如果组是固定的(用户,经理),您可以使用以下内容:

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

否则你需要使用这样的解决方案:

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;

请参阅小提琴here

如果您需要创建视图,只需使用以下代码修改上述代码:

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;