用名称替换GROUP_CONCAT列中的ID

时间:2018-06-15 09:24:51

标签: mysql

我有三个表,我成功加入了以下sql查询

SELECT `bonuses`.`id`, `bonuses`.`bonus_name`, `bonuses`.`size`, creatorName.`name`, GROUP_CONCAT(DISTINCT bonus_user.user_id ORDER BY bonus_user.user_id SEPARATOR ', ') as bonusUsers from `bonuses`
inner join `users` as creatorName on `bonuses`.`created_from` = creatorName.`id`
inner join `bonus_user` on `bonuses`.`id` = `bonus_user`.`bonus_id`
group by `bonuses`.`id`

我得到的结果如下。作为进一步的步骤,我想替换列中的ID" bonusUsers"来自users表中的名称。我该如何管理?

+----+--------------+------+--------------+--------------+
| id |  bonus_name  | size |     name     |  bonusUsers  |
+----+--------------+------+--------------+--------------+
| 3  | Bonus Test 3 |   5  |     Test1    |    1, 2, 3   |
| 4  | Bonus Test 4 |   3  |     Test1    |    1, 2, 3   |
+----+--------------+------+--------------+--------------+

用户

+----+-------+
| id | name  |
+----+-------+
| 1  | Test1 |
| 2  | Test2 |
| 3  | Test3 |
+----+-------+

奖金

+----+--------------+------+--------------+
| id |  bonus_name  | size | created_from |
+----+--------------+------+--------------+
| 1  | Bonus Test 1 |   1  |       1      |
| 2  | Bonus Test 2 |   1  |       1      |
| 3  | Bonus Test 3 |   5  |       1      |
| 4  | Bonus Test 4 |   3  |       1      |
+----+--------------+------+--------------+

bonus_user

+----+----------+------------+
| id | bonus_id | bonus_user |
+----+----------+------------+
| 1  |     3    |      1     |
| 2  |     3    |      2     |
| 3  |     3    |      3     |
| 4  |     4    |      1     |
| 5  |     4    |      2     |
| 6  |     4    |      3     |
+----+----------+------------+

2 个答案:

答案 0 :(得分:0)

与用户表进行另一次联接

RewriteEngine On

RewriteCond %{REQUEST_URI} ^/stuff$

RewriteRule .? - [S=1]

RewriteRule (.*)  https://www.other-website.com  [R,L]

Demo

答案 1 :(得分:0)

您需要对users表进行别名并将其连接到bonus_user表,以从别名表中获取用户的名称

SELECT `bonuses`.`id`, `bonuses`.`bonus_name`, `bonuses`.`size`, creatorName.`name`,
GROUP_CONCAT(DISTINCT user_names.name ORDER BY bonus_user.user_id SEPARATOR ', ') as bonusUsers from `bonuses`
inner join `users` as creatorName on `bonuses`.`created_from` = creatorName.`id`
inner join `bonus_user` on `bonuses`.`id` = `bonus_user`.`bonus_id`
inner join `users AS user_names` on `bonus_user`.`bonus_user` = `user_names`.`id`
group by `bonuses`.`id`

这也有助https://www.w3schools.com/sql/sql_alias.asp