sql >> Database >  >> RDS >> Mysql

hoe tekst in cel te vervangen door gegevens in een andere tabel in mysql

nou, je zou iets in de trant van deze kunnen proberen:

dit is een testopstelling:

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)

Even uitleggen; eerst kruis je beide tabellen samen en dat zou een cartesiaans product moeten opleveren, zoals:

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)

vanaf dat punt selecteert u gewoon rijen waarvan de ene tekenreeks in een andere is opgenomen (INSTR(permission, t2id) => machtigingen toewijzen aan ids), u krijgt dit:

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)

aggregeer nu gewoon resultaten met 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. Hoe lid te worden van de eerste rij

  2. Tabelvariabele maken in MySQL

  3. Hoe maak je een nieuwe databaseverbinding in django

  4. Gemiste optimalisaties omzeilen