我有一个桌子'组织'与字段ID和父。 parent指的是同一个表(自引用键)。
我有另一个名为' user_organization'的表,其中我有user_id和org_id。 org_id链接到' organization'中的ID表
现在我想创建一个视图,使用这两个包含user_id和organization_id的表。由于一个组织的成员将是所有子组织的成员,因此该视图将包含来自实际user_organization表的额外值。
如何创建此视图?
答案 0 :(得分:0)
似乎只有SQL select语句才有可能。
https://stackoverflow.com/a/9056945/721597
但是在功能的帮助下,我设法做到了。
我创建了一个名为IsRelated(id,parent)的函数 - 它告诉id是否与父相关(如果id = parent它们是相关的):
CREATE FUNCTION `IsRelated`(`GivenID` VARCHAR(10), ParentId VARCHAR(10)) RETURNS boolean
BEGIN
DECLARE related boolean;
DECLARE ch INT;
SET related = FALSE;
IF ParentId = GivenID THEN
SET related = TRUE;
ELSE
SET ch = GivenID;
myloop: WHILE ch IS NOT NULL DO
SELECT IF(parent_org_id = ch, NULL, parent_org_id) INTO ch FROM
(SELECT parent_org_id FROM organizations WHERE id = ch) A;
IF ch IS NOT NULL AND ch = ParentId THEN
SET related = TRUE;
LEAVE myloop;
END IF;
END WHILE;
END IF;
RETURN related;
END
然后我创建一个这样的视图:
CREATE VIEW `v_all_orgs` AS SELECT o1.id AS org, o2.id AS related_to
FROM organizations o1
JOIN organizations o2 ON IsRelated(o1.id, o2.id)
通过这两个,我创建了我所需要的视图:
CREATE VIEW `v_all_user_orgs` AS SELECT DISTINCT user_organizations.user_id, v_all_orgs.org as org_id, user_organizations.created_ts
FROM user_organizations JOIN v_all_orgs ON v_all_orgs.related_to = user_organizations.org_id OR v_all_orgs.org = user_organizations.org_id
ORDER BY user_organizations.user_id, v_all_orgs.org