0

我需要你帮忙。

我在 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但是:新表应该是这样的

*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中制作它?

4

2 回答 2

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(permission, 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;
于 2012-09-06T15:25:57.290 回答
0

我想你必须处理case

但我认为你试图做的是绝对错误的。为什么要创建这样 2 个表?

于 2012-09-06T11:59:40.900 回答