1

我有一张users,inductions和的表格user_inductions

  • users表有idand name,
  • inductions表有idname, 和
  • user_inductions有和。_ id_user_idinduction_id

我想返回一份所有诱导和做过诱导的人的列表。但是,我已经这样做了,因为我希望创建一个如下所示的表格。我不确定如何编辑查询,所以我可以按我的意愿取回信息。

------------------------------------------------------------------------------------
| name    | tennis | cricket | rugby | squash | football | Table tennis |   etc    |
------------------------------------------------------------------------------------
| Bob     |   0    |   1     |   0   |    1   |    1     |     0        |          |
------------------------------------------------------------------------------------
| paul    |   1    |   1     |   1   |    1   |    0     |     0        |          |
------------------------------------------------------------------------------------

我想遍历数据,以便在顶部获得归纳列表,然后每个用户如果已被引导到该主题,则以 1 下降,如果没有,则以 0 下降。我有几个查询,但他们只返回所有用户只返回他们所做的归纳或归纳和做过的人。

例如:

SELECT CONCAT(  `f_name` ,  ' ',  `l_name` ) AS user, GROUP_CONCAT( pmainductions.name
ORDER BY pmainductions.id ) AS induction
FROM users
LEFT JOIN pmainduction_user ON users.id = pmainduction_user.user_id
LEFT JOIN pmainductions ON pmainductions.id = pmainduction_user.pmainduction_id
GROUP BY users.id

这会产生

bob | cricket,squash,football

paul| tennis,cricket,rugby,squash

任何帮助,将不胜感激。谢谢 :)

4

1 回答 1

2

尝试这个:

SELECT 
  CONCAT(  `f_name` ,  ' ',  `l_name` ) AS user, 
  MAX(CASE WHEN pmainductions.name = 'tennis' THEN 1 ELSE 0 END) AS 'tennis',
  MAX(CASE WHEN pmainductions.name = 'cricket' THEN 1 ELSE 0 END) AS 'cricket',
  MAX(CASE WHEN pmainductions.name = 'rugby' THEN 1 ELSE 0 END) AS 'rugby',
  ...
FROM users
LEFT JOIN pmainduction_user ON users.id         = pmainduction_user.user_id
LEFT JOIN pmainductions     ON pmainductions.id = pmainduction_user.pmainduction_id
GROUP BY users.id;

如果您对每个用户有未知数量的感应,并且您想动态地执行此操作,您可以这样做:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT CONCAT('MAX(IF(p.Name = ''',
      p.Name, ''', 1, 0)) AS ', '''',   p.Name , '''')
  ) INTO @sql
FROM users u
LEFT JOIN user_inductions up ON u.id = up.user_id
LEFT JOIN inductions      p ON p.id = up.induction_id;

SET @sql = CONCAT('SELECT u.name AS user,' ,
                  @sql, ' FROM users u ',
                  ' LEFT JOIN user_inductions up ',
                  ' ON u.id = up.user_id',
                  ' LEFT JOIN inductions      p     ',
                  ' ON p.id = up.induction_id ',
                  ' GROUP BY u.id');
SELECT @sql;

prepare stmt 
FROM @sql;

execute stmt;

SQL 小提琴演示

这会给你类似的东西:

| USER | TENNIS | CRICKET | RUGBY | SQUASH | FOOTBALL | TABLE TENNIS | TWO WORDS |
----------------------------------------------------------------------------------
|  bob |      1 |       1 |     1 |      1 |        1 |            0 |         0 |
| paul |      1 |       1 |     1 |      1 |        1 |            1 |         1 |
于 2013-01-06T09:06:46.420 回答