我需要在选择查询时从表格的值中替换表格的字段值。
例如:
表1:
Org Permission
--------------------------------------
Company1 1,3,7
Company2 1,3,8
表2:
Permission Permission
--------------------------------------
1 Read
3 Write
7 Execute
8 Delete
我需要这样:
Org Permission
--------------------------------------
Company1 Read,Write,Execute
Company2 Read,Write,Delete
答案 0 :(得分:0)
我一直关注你的帖子,因为它在Oracle中被标记:D
在oracle中它有很多可能的方式,但在mysql中你必须在程序的帮助下遵循它:
架构:
create table table1 (org varchar(50), permission_id varchar(50));
create table table2 (permission_id int, permission_name varchar(50));
insert into table1 values ('Company1','1,3,7'),('Company2','1,3,8');
insert into table2 values (1,'Read'),(3,'Write'),(7,'Execute'),(8,'Delete');
步骤:
DELIMITER $$
DROP PROCEDURE IF EXISTS `Update_Table_data`$$
CREATE PROCEDURE `Update_Table_data`()
BEGIN
declare max_row int;
declare p1 int;
Set p1 = 0;
SET max_row = (SELECT max(@i:=@i+1) AS row_num FROM table2 AS t,(SELECT @i:=0) AS foo);
label1: LOOP
set p1 = p1 + 1;
IF p1 <= max_row THEN
UPDATE Table1
SET permission_id =
replace(permission_id, (select permission_id from
(SELECT @i:=@i+1 AS row_num ,t.* FROM table2 AS t,(SELECT @i:=0) AS foo) a
where row_num = p1),
(select permission_name from
(SELECT @i:=@i+1 AS row_num ,t.* FROM table2 AS t,(SELECT @i:=0) AS foo) a
where row_num = p1));
Iterate label1;
END IF;
LEAVE label1;
END LOOP label1;
-- SET @x = p1;
END$$
DELIMITER ;
然后拨打电话更新您的值:
call Update_Table_data;
希望有所帮助:)
答案 1 :(得分:0)
有关初始数据,请参阅SQLFiddle,这是结果数据SQLFiddle
UPDATE
organization
SET
permisson = (SELECT
GROUP_CONCAT(VALUE)
FROM
( SELECT
org,
SUBSTRING_INDEX(permisson,',',1) AS `permisson`
FROM
organization
UNION
SELECT
org,
SUBSTRING_INDEX(SUBSTRING_INDEX(permisson,',',2),',',-1) AS `permisson`
FROM
organization
UNION
SELECT
org,
SUBSTRING_INDEX(permisson,',',-1) AS `permisson`
FROM
organization
) AS t
JOIN
permission p
WHERE
p.p_id = t.permisson AND
t.org = organization.org
GROUP BY org
)
答案 2 :(得分:-1)
尝试使用REPLACE替换您的号码。仅当您使用单个数字值进行许可时才能正常工作。
SQL = " SELECT Org, REPLACE(REPLACE(REPLACE(REPLACE(Permission,"1","Read'"),"3","Write'"),"7","Execute'"),"8","Delete'") as Permission FROM myTable "