我需要你的帮助。
我在MYSQL中有一个像这样的表
*TABLE1*
id | permission
-- | ----------
a1 | 1,2,3,4,5
v2 | 2,3,4
r1 | 1,3,4,5
b4 |
h7 | 4,5
我有另一张桌子
*TABLE2*
id | permission
-- | ----------
1 | Allow
2 | Not Allow
3 | Disabled
4 | WOW
5 | Grant
我想选择TABLE1 JOIN TABLE2 BUT:新表应该是这样的
*NEW_TABLE*
id | permission
-- | ----------
a1 | Allow,Not Allow,Disabled,WOW,Grant
v2 | Not Allow,Disabled,WOW
r1 | Allow,Disabled,WOW,Grant
b4 |
h7 | WOW,Grant
有没有办法在MYSQL中实现?
答案 0 :(得分:2)
你可以尝试这些方法:
这是测试设置:
mysql> select * from table1;
+------+------------+
| id | permission |
+------+------------+
| a1 | 1, 2, 3, 4 |
| v2 | 2, 3, 4 |
+------+------------+
2 rows in set (0.01 sec)
mysql> select * from table2;
+------+------------+
| id | permission |
+------+------------+
| 1 | Allow |
| 2 | Not Allow |
| 3 | Disabled |
+------+------------+
3 rows in set (0.01 sec)
mysql> select id, GROUP_CONCAT(t2perm) from (SELECT t1.*, t2.id as t2id, t2.permission as t2perm from table2 t2 cross join table1 t1) crs where INSTR(permission, t2id) > 0 group by id;
+------+--------------------------+
| id | GROUP_CONCAT(t2perm) |
+------+--------------------------+
| a1 | Allow,Not Allow,Disabled |
| v2 | Not Allow,Disabled |
+------+--------------------------+
2 rows in set (0.00 sec)
解释一下;首先你交叉连接两个表,这应该导致笛卡尔积,如下所示:
mysql> SELECT * from table2 cross join table1;
+------+------------+------+------------+
| id | permission | id | permission |
+------+------------+------+------------+
| 1 | Allow | a1 | 1, 2, 3, 4 |
| 1 | Allow | v2 | 2, 3, 4 |
| 2 | Not Allow | a1 | 1, 2, 3, 4 |
| 2 | Not Allow | v2 | 2, 3, 4 |
| 3 | Disabled | a1 | 1, 2, 3, 4 |
| 3 | Disabled | v2 | 2, 3, 4 |
+------+------------+------+------------+
6 rows in set (0.00 sec)
从那时起,只需选择另一个包含一个字符串的行(INSTR(权限,t2id)=>映射权限到ids),你最终会得到这个:
mysql> select * from (SELECT t1.*, t2.id as t2id, t2.permission as t2perm from table2 t2 cross join table1 t1) crs where INSTR(permission, t2id) > 0;
+------+------------+------+-----------+
| id | permission | t2id | t2perm |
+------+------------+------+-----------+
| a1 | 1, 2, 3, 4 | 1 | Allow |
| a1 | 1, 2, 3, 4 | 2 | Not Allow |
| v2 | 2, 3, 4 | 2 | Not Allow |
| a1 | 1, 2, 3, 4 | 3 | Disabled |
| v2 | 2, 3, 4 | 3 | Disabled |
+------+------------+------+-----------+
5 rows in set (0.00 sec)
现在只使用GROUP_CONCAT ...
汇总结果select id, GROUP_CONCAT(t2perm) from (SELECT t1.*, t2.id as t2id, t2.permission as t2perm from table2 t2 cross join table1 t1) crs where INSTR(permission, t2id) > 0 group by id;
答案 1 :(得分:0)
我想你必须与cases合作。
但我认为你所要做的就是绝对错误。你为什么要创建这样的2个表?