1

Joomla 有三个表:

用户:

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

团体:

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

用户组地图:

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 中是否有该用户的记录。

有意义吗?

4

1 回答 1

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;

在此处查看小提琴。

如果需要创建视图,只需修改上面的代码:

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;
于 2013-02-26T22:11:30.750 回答