Self referencing table many to many relationship
I am in a bit of a logic pickle, and I was wondering if someone could help me out.
I have a table in a database I am designing called document, it holds information on surprisingly on documents in our DMS.
I want to create the notion that a document can have multiple related documents, and those documents can be the related documents for many documents.
So it is a self referencing table, I have done these before so no big deal, but this time is a many to many relation, it wasnt before.
Maybe something like:
document
docid (pk)
related_doc
docid (pk) (fk to document.docid)
related_docid (pk) fk to document.docid)
Does anyone have any experience with this or any advise I might find sueful?
Thanks!
A junction table can be used to resolve a many-to-many relationship as is in your example. There are two PK/FK relationships between document and related_document table. This will prevent denormalization of data.
The other option could be to have just one table with two columns (parent_doc_id and child_doc_id) and have a PK constraint on both the columns - just like bill-of-materials.
But I think the approach you have in your posting will work well.
Shakti
http://www.impact-sol.com
Developers of Guggi Oracle - Tool for DBAs and Developers
Similar Messages
-
Self Referencing Tables...
I have a self-referencing table (a Topic can be a response to another Topic) and read one of Frank Nimphius' blogs on this subject, posted on the ADF board for advise. As a result I created the read-only ViewObject to set up this tree relationship and set it to be exposed to the App Module.
Do I need to do more to it than that for JHeadstart to generate the right page defs? Any advise on setting this up cleanly? My user interface must present a page in which users can post new Topics, view topics in a heirarchy (response thread, like in this forum) and respond to Topics or responses. A response is a Topic that references another (parent) Topic. I have to believe this has been done before a million times but am not sure myself how to do it.
Thanks!Steve,
I've read the section and am getting this error:
(oracle.jbo.SQLStmtException) JBO-27122: SQL error during statement preparation. Statement: SELECT Topic.SUBJECT, Topic.ROW_ID, Status.STATUS_CHOICE, Status.ROW_ID AS ROW_ID11, Topic.CREATED_BY, Topic.CREATION_DATE, Response.SUBJECT AS SUBJECT1, Response.CREATION_DATE AS CREATION_DATE1, Response.ROW_ID AS ROW_ID12, Response.CREATED_BY AS CREATED_BY1 FROM TOPIC Topic, RESPONSE Response, STATUS Status WHERE (Topic.ROW_ID = Response.MASTER_ID (+)) AND (Topic.TOPIC_STATUS_ID = Status.ROW_ID) CONNECT BY PRIOR Topic.ROW_ID = Response.MASTER_ID (+) OR Response.ROW_ID = Response.MASTER_ID (+) ORDER BY SUBJECT,CREATION_DATE1
----- LEVEL 1: DETAIL 0 -----
(java.sql.SQLException) ORA-01436: CONNECT BY loop in user data
I have a table called Topic with a Pk called ROW_ID and another table called Response with a Pk called ROW_ID and an Fk called MASTER_ID. A Topic can have many Responses and a Response can also have many Responses. The parent ID could point to either a Topic or a Response. There's no limit on how many levels this can continue. There's a Status table also from which I want to show the text value of the Status for the Topic row (not the Status ROW_ID)
I have a View Object including entities: Topic, Response & Status
I tried the SQL query as:
(Topic.ROW_ID = Response.MASTER_ID (+)) AND (Topic.TOPIC_STATUS_ID = Status.ROW_ID) CONNECT BY PRIOR Topic.ROW_ID = Response.MASTER_ID (+) OR Response.ROW_ID = Response.MASTER_ID (+)
Hoping to have this result:
Topic A
-Response A (to Topic A)
--Response B (to A)
---Response C (to B)
-Response D (to Topic A)
Topic B
Topic C
What am I doing wrong?
Is there a guide that explains better using JHeadstart with JDeveloper (rather than Oracle Designer, which we don't use)? The developer's guide for JHeadstart is hard to translate for use with JDeveloper...
Thanks!! -
Self referencing table and SQL statement
In my database, I have a self-referencing table, the table itself is for projects, and it allows users to get a hierarchical view of the company.
Here is the SQL (modifier is the term we use for project code, BBCI is the top project)
SELECT
modifier, modifierDescription, level
FROM
modifier
WHERE
level <= 2
CONNECT BY PRIOR
modifier = parentModifier
START WITH modifier = 'BBCI'
ORDER BY level
That perticular query gets the first two levels in the structure. I use this information to produce a tree structure in a web app.
But users have requested it would be good if in the tree structure is showed an + or - depending on whether there were anymore children under each parent, or better still the number of children under it, for example
BBCI
+ BBCI_CHILD
+ BBCI_CHILD2
- BBCI_CHILD3
or
BBCI
+ BBCI_CHILD (3 projects underneath)
+ BBCI_CHILD2 (2 projects underneath)
- BBCI_CHILD3 (0 projects underneath)
I am really stumped on this issue, and I am sure there is a way to do this in the web app, so for example do a query for each child node to see how many child nodes are underneath, but I figure it would be a lot tidier and faster if I could do it from a single SQL statement. Unfortunately I have tried to do this and am very much stuck.
If you need more information please let me know
Thanks!
JonYou may be able to do this using analytical functions but it depends on the Oracle version you are using. It can also be done with standard SQL - you just need to count the number of child rows for each modifier/project first and supply that list as an in-line view:
SELECT decode(modifier,'X',null,decode(child_rows,null,'-','+')),
m.modifier,
decode(modifier,'X',null,'('||nvl(cq.child_rows,0)||' projects underneath)')
FROM modifier m,
(select parentModifier,
count(parentModifier) child_rows
from modifier
where parentModifier is not null
group by parentModifier) cq
WHERE m.modifier=cq.parentModifier(+)
AND level <= 2
CONNECT BY PRIOR
m.modifier = m.parentModifier
START WITH modifier = 'X'
ORDER BY level, modifier;
which gives you something like...
D MODIFIER DECODE(MODIFIER,'X',NULL
X
- Y1 (0 projects underneath)
+ Y2 (2 projects underneath)
+ Y3 (3 projects underneath)
The decode stuff is just to show you the result, you can format the output in your calling code. Just extend the columns to include everything you want, modifierDescription etc..
Hope this helps. -
Self referencing table and contraint
Hi,
I have a self referencing table, used to store information on projects in an organization. There is a pimary key (modifier) and a foreign key to the modifier field (parentModifier)
Note: (modifier = project in the organization)
Basically, the parentModifier cannot be equal to the modifier in the same table, or equal to any of its children, otehrwise you get wierd recursive relationships. Its like saying you cannot be your own father, or one of your children cannot be your father. To get a list of the modifiers the parentModifier cannot be, the following statement can be used:
select
modifier
from
modifier
where
modifier = 'A'
and
level >= 1
connect by prior
modifier = parentModifier
start with
modifier = 'A'
order by
level;
So, now, I guess the way to do this is perform that query in a trigger before each row is being updated, so the pseudo code would be something like:
BEFORE UPDATE ON modifier
FOR EACH ROW
DECLARE
modifierToChange varchar2(255);
modifierList ???;
BEGIN
select
modifier
into
modifierList
from
modifier
where
modifier = 'A'
and
level >= 1
connect by prior
modifier = parentModifier
start with
modifier = 'A'
order by
level;
if modifierToChange in modifierList
return error
else
execute query
end if
END
As you can see my PL/SQL is limitied. At the moment I can handle this at the application layer (in php), but if the admin going to SQL Plus and starts to fiddle, they can easy break the system, by setting an invalid relationship.
I was wondeirng, if anyone could give me some help or advice, it would be fantastic,
Thanks!Having a unique key on mod_id would be enough to make sure the same element is not in the structure more than once. By allowing it to happed you will have all the descendants of the dup element following it when you walk the tree.
Let's say this is the intended behavior.
Consider the following test scenario:
create table modifier (
mod_id varchar2(10),
parent_mod_id varchar2(10)
insert into modifier (mod_id, parent_mod_id) values ('a', null);
insert into modifier (mod_id, parent_mod_id) values ('aa', 'a');
insert into modifier (mod_id, parent_mod_id) values ('ab', 'a');
insert into modifier (mod_id, parent_mod_id) values ('ac', 'a');
insert into modifier (mod_id, parent_mod_id) values ('aaa', 'aa');
insert into modifier (mod_id, parent_mod_id) values ('aab', 'aa');
insert into modifier (mod_id, parent_mod_id) values ('aac', 'aa');
insert into modifier (mod_id, parent_mod_id) values ('aba', 'ab');
insert into modifier (mod_id, parent_mod_id) values ('abb', 'ab');
insert into modifier (mod_id, parent_mod_id) values ('abc', 'ab');
insert into modifier (mod_id, parent_mod_id) values ('aca', 'ac');
insert into modifier (mod_id, parent_mod_id) values ('acb', 'ac');
insert into modifier (mod_id, parent_mod_id) values ('acc', 'ac');
insert into modifier (mod_id, parent_mod_id) values ('b', null);
insert into modifier (mod_id, parent_mod_id) values ('ba', 'b');
insert into modifier (mod_id, parent_mod_id) values ('bb', 'b');
insert into modifier (mod_id, parent_mod_id) values ('bc', 'b');
insert into modifier (mod_id, parent_mod_id) values ('baa', 'ba');
insert into modifier (mod_id, parent_mod_id) values ('bab', 'ba');
insert into modifier (mod_id, parent_mod_id) values ('bac', 'ba');
insert into modifier (mod_id, parent_mod_id) values ('bba', 'bb');
insert into modifier (mod_id, parent_mod_id) values ('bbb', 'bb');
insert into modifier (mod_id, parent_mod_id) values ('bbc', 'bb');
insert into modifier (mod_id, parent_mod_id) values ('bca', 'bc');
insert into modifier (mod_id, parent_mod_id) values ('bcb', 'bc');
insert into modifier (mod_id, parent_mod_id) values ('bcc', 'bc');
commit;
SQL> select lpad(' ', 2 * (level - 1)) || mod_id item
2 from modifier
3 start with parent_mod_id is null
4 connect by prior mod_id = parent_mod_id;
ITEM
a
aa
aaa
aab
aac
ab
aba
abb
abc
ac
aca
acb
acc
b
ba
baa
bab
bac
bb
bba
bbb
bbc
bc
bca
bcb
bcc
26 rows selected
Create a function to verify if a mod_id already is parent_mod_id's ascendant or descendant:
create or replace function exists_in_parents_branch
i_mod_id in varchar2
,i_parent_mod_id in varchar2
) return boolean is
pragma autonomous_transaction;
v_dummy varchar2(10);
begin
select mod_id
into v_dummy
from (select mod_id
from modifier
where mod_id = i_mod_id
connect by prior mod_id = parent_mod_id
start with mod_id = i_parent_mod_id
union
select mod_id
from modifier
where mod_id = i_mod_id
connect by prior parent_mod_id = mod_id
start with mod_id = i_parent_mod_id);
return true;
exception
when no_data_found then
return false;
end exists_in_parents_branch;
Create a trigger that calls the function above for every insert and update
create or replace trigger biu_modifier
before insert or update on modifier
for each row
begin
if exists_in_parents_branch(:new.mod_id, :new.parent_mod_id) then
raise_application_error(-20000, 'Cannot insert or update because of recursive relationship.');
end if;
end biu_modifier;
You are all set.
Here is a statement that should fail:
SQL> insert into modifier (mod_id, parent_mod_id) values ('bcc', 'b');
insert into modifier (mod_id, parent_mod_id) values ('bcc', 'b')
ERROR at line 1:
ORA-20000: Cannot insert or update because of recursive relationship.
ORA-06512: at "RC.BIU_MODIFIER", line 3
ORA-04088: error during execution of trigger 'RC.BIU_MODIFIER'
Here is a statement that should succeed:
SQL> insert into modifier (mod_id, parent_mod_id) values ('aaaa','aaa');
1 row created. -
Best practice: self referencing table
Hallo,
I want to load a self referencing table to my enterprise area in the dwh. I am not sure how to do this. What if a record references to another record which is inserted later in the same etl process? There is now way to sort, because it is possible that record a references to record b and record b references to record a. Disabling the fk constraint is not a good idea, because this doesn't prevent that invalid references will be loaded? I am thinking of building two mappings, one without the self referencing column and the other only with it, but that would cause approx. twice as much running time. Any other solutions?
Regards,
TorstenMind sharing the solution? Would be interested to hear your solution (high level).
Jean-Pierre -
How to build query to get tree architecture of self referencing table
Dear all,
I have the following table design :
This is a self referencing table representing a set of SubCategories which can have parent sub categories or not. I did not show here the Category table.
If the Subcategory has the ParentSubCategory ID = null, then this is a root subcategory otherwise it is a child of a parent sub category.
What I am looking for is the easy way to display the structure level by ProductCategoryID ?
Thanks for helpsyou can use a recursive logic based on CTE for that
something like this would be enough
;WITH ProdSubCat_Hiererchy
AS
SELECT psc.ProductSubCategoryID,c.CategoryName,psc.ParentSubCategoryID, psc.Name,CAST(psc.Name AS varchar(max)) AS [Path],1 AS [level]
FROM ProductSubCategory psc
INNER JOIN Category c
ON c.CategoryID = psc.ProductCategoryID
WHERE psc.ParentSubCategoryID IS NULL
UNION ALL
SELECT psc.ProductSubCategoryID,c.CategoryName,psc.ParentSubCategoryID, psc.Name,CAST(psch.[Path] + '/' + psc.Name AS varchar(max)) AS [Path],psch.[level] + 1
FROM ProductSubCategory psc
INNER JOIN Category c
ON c.CategoryID = psc.ProductCategoryID
INNER JOIN ProdSubCat_Hiererchy psch
ON psch.ProductSubCategoryID = psc.ParentSubCategoryID
SELECT *
FROM ProdSubCat_Hiererchy
ORDER BY LEFT([Path],CHARINDEX('/',[Path]+'/')-1),[Level]
OPTION (MAXRECURSION 0)
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
JPA: How to initialise an entity for a self-referencing table?
I am working on a project that requires a self-referencing table:
mysql> show create table attributes\G
*************************** 1. row ***************************
Table: attributes
Create Table: CREATE TABLE `attributes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`parent` int(11) DEFAULT NULL,
`type` int(11) DEFAULT NULL,
`name` varchar(128) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `parent` (`parent`),
KEY `type` (`type`),
CONSTRAINT `attributes_ibfk_1` FOREIGN KEY (`parent`) REFERENCES `attributes` (`id`),
CONSTRAINT `attributes_ibfk_2` FOREIGN KEY (`type`) REFERENCES `attributes` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=latin1
I used NetBeans to generate an entity class from the table:
@Entity
@Table(name = "attributes")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Attributes.findAll", query = "SELECT a FROM Attributes a"),
@NamedQuery(name = "Attributes.findById", query = "SELECT a FROM Attributes a WHERE a.id = :id"),
@NamedQuery(name = "Attributes.findByName", query = "SELECT a FROM Attributes a WHERE a.name = :name")})
public class Attributes implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Size(max = 128)
@Column(name = "name")
private String name;
@OneToMany(mappedBy = "parent")
private Collection<Attributes> attributesCollection;
@JoinColumn(name = "parent", referencedColumnName = "id")
@ManyToOne
private Attributes parent;
@OneToMany(mappedBy = "type")
private Collection<Attributes> attributesCollection1;
@JoinColumn(name = "type", referencedColumnName = "id")
@ManyToOne
private Attributes type;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "attributes")
private Collection<ItemAttributes> itemAttributesCollection;
@OneToMany(mappedBy = "ivalue")
private Collection<ItemAttributes> itemAttributesCollection1;
But how can I write a constructor for this entity? The auto-generated code gets around the issue by doing nothing; the constructor is empty. I can't help thinking that if I set the parent and type references to anything with new Attributes(), then it will recurse out of control. What else can/shall I do? I know how to rewrite it to not use the entity relations, but I'd prefer to make it work.Cymae wrote:
I don't want to call the hash table creation method because from what i understand about interfaces the idea is that your main method doesnt know the table is actually a hash table...is that right?That's not exactly the idea. The idea to use the interface as the type instead of the implementation, is that your class probably doesn't need to know the full type. This makes it easy to change the implementation of the interface if needed. However, somebody at some point has to create the concrete object, a HashTable.
Basically, an interface describes a behavior, and a class that implements an interface decides how to actually perform this behavior. It is obviously impossible to perform the behavior if you are not told how to perform it.
Table table = new HashTable() is the correct way to do it. This means that if you ever need you Table implementation to change, the only thing you need to change in your whole class is this line. For example you might want Table table = new FileTable(). -
Query output help: Display self-referencing table
Hello,
I'm trying to display in a cfoutput a self-referencing table.
I'll start by showing some of the data in the table.
There are only 3 columns, pl_id (auto increment id pri-key),
pl_name and pl_parent_id (it's 0 if it's a parent, otherwise it's
the pl_id value for the parent).
pl_id pl_name pl_parent_id
1 Country 0
2 Food 0
3 US 1
4 Japan 1
5 Hamburger 2
6 Idaho 3
7 Florida 3
8 Cheese 2
What I'm trying to output is something like this:
Country - US - Idaho (3 levels here) or
Country - US - Florida (or if there are only 2 levels like
the next line)
Food - Cheese
I've tried using a cfoutput with a cfloop as well as grouping
but not having any luck. Could someone clear my clouded head on
this one?
thanks much,
Joe
ps. Adobe should really use a fixed width font for these
forums, it's impossible to line up table info!JoeNH2k wrote:
> It would be nice if it were that easy, I (of course)
tried that. The sort order
> of the query doesn't matter. The data is not sorted once
the function runs. The
> sort has to come after the select box is populated by
the function. I need to
> get the data at this point and sort it, probably somehow
creating a structure
> or array from this data and sorting that(?).
>
<cfset myArr = ArrayNew(1)>
<cfloop query="qryGetAll">
<cfset temp = ArrayAppend(myArr,
"#getNameWithParent(pl_id)#")>
</cfloop>
<cfset ArraySort(myArr, "textnocase", "asc")>
<cfset myList = ArrayToList(myArr, ",")>
then loop through myList to populate your <select>...
how about that?
Azadi Saryev
Sabai-dee.com
Vientiane, Laos
http://www.sabai-dee.com -
ORA-02291 during MERGE on self-referenced table
Hello,
I encountered error ORA-02291 when I tried to use MERGE statement on the table with "self-referenced" foreign key. Using the foreign key deferrable did not help. The only one thing, which helped me, was using errorlog table. See the demonstration:
Working as common user:
SQL> CONNECT scott/tiger
First of all, I create table and (not deferrable) constraints:
CREATE TABLE fkv (
id NUMBER(1) CONSTRAINT nn_fkv_id NOT NULL,
parent_id NUMBER(1) CONSTRAINT nn_fkv_paid NOT NULL
ALTER TABLE fkv ADD CONSTRAINT pk_fkv_id PRIMARY KEY (id);
ALTER TABLE fkv ADD CONSTRAINT fk_fkv_paid FOREIGN KEY (parent_id) REFERENCES fkv(ID) NOT DEFERRABLE;
INSERT is working well:
INSERT INTO fkv (
id,
parent_id
SELECT
1,
1
FROM
DUAL;
COMMIT;
1 rows inserted.
commited.
MERGE statement using UPDATE branch is working well too:
MERGE INTO fkv USING (
SELECT
1 AS ID,
1 AS PARENT_ID
FROM
DUAL
) a
ON (
fkv.id = a.id
WHEN MATCHED THEN
UPDATE SET
fkv.parent_id = a.parent_id
WHERE
A.ID IS NOT NULL
DELETE WHERE a.id IS NULL
WHEN NOT MATCHED THEN
INSERT (
ID,
parent_id
VALUES (
A.ID,
A.PARENT_ID);
COMMIT;
1 rows merged.
commited.
And now is coming the strange behaviour:
MERGE INTO fkv USING (
SELECT
2 AS id,
2 AS PARENT_ID
FROM
DUAL
) a
ON (
fkv.id = a.id
WHEN MATCHED THEN
UPDATE SET
fkv.parent_id = a.parent_id
WHERE
A.ID IS NOT NULL
DELETE WHERE a.id IS NULL
WHEN NOT MATCHED THEN
INSERT (
ID,
parent_id
VALUES (
A.ID,
A.PARENT_ID);
SQL Error: ORA-02291: integrity constraint (SCOTT.FK_FKV_PAID) violated - parent key not found
ROLLBACK;
rollback complete.
Ok, even it is not a good solution, I try deferrable constraint:
ALTER TABLE fkv DROP CONSTRAINT fk_fkv_paid;
ALTER TABLE fkv ADD CONSTRAINT fk_fkv_paid FOREIGN KEY (parent_id) REFERENCES fkv(id) DEFERRABLE INITIALLY DEFERRED;
table FKV altered.
table FKV altered.
MERGE INTO fkv USING (
SELECT
2 AS id,
2 AS PARENT_ID
FROM
DUAL
) a
ON (
fkv.id = a.id
WHEN MATCHED THEN
UPDATE SET
fkv.parent_id = a.parent_id
WHERE
A.ID IS NOT NULL
DELETE WHERE a.id IS NULL
WHEN NOT MATCHED THEN
INSERT (
ID,
parent_id
VALUES (
A.ID,
A.PARENT_ID);
1 rows merged.
COMMIT;
SQL Error: ORA-02091: transaction rolled back
ORA-02291: integrity constraint (SCOTT.FK_FKV_PAID) violated - parent key not found
... deffered constraint did not help :-(
Let's try another way - errorlog table; for the first with the not deferrable constraint again:
ALTER TABLE fkv DROP CONSTRAINT fk_fkv_paid;
ALTER TABLE fkv ADD CONSTRAINT fk_fkv_paid FOREIGN KEY (parent_id) REFERENCES fkv(ID) NOT DEFERRABLE;
table FKV altered.
table FKV altered.
BEGIN
sys.dbms_errlog.create_error_log (
dml_table_name => 'FKV',
err_log_table_name => 'ERR$_FKV'
END;
anonymous block completed
Toys are prepared, let's start with error logging:
MERGE INTO fkv USING (
SELECT
2 AS id,
2 AS PARENT_ID
FROM
DUAL
) a
ON (
fkv.id = a.id
WHEN MATCHED THEN
UPDATE SET
fkv.parent_id = a.parent_id
WHERE
A.ID IS NOT NULL
DELETE WHERE a.id IS NULL
WHEN NOT MATCHED THEN
INSERT (
ID,
parent_id
VALUES (
A.ID,
A.PARENT_ID)
LOG ERRORS INTO err$_fkv;
1 rows merged.
Cannot belive, running SELECT for confirmation:
SELECT * FROM err$_fkv;
SELECT * FROM fkv;
no rows selected
ID PARENT_ID
1 1
2 2
Ok, COMMIT:
COMMIT;
commited.
SELECT for confirmation again:
SELECT * FROM err$_fkv;
SELECT * FROM fkv;
no rows selected
ID PARENT_ID
1 1
2 2
Using deffered constraint and error logging is working well too.
Metalink and Google did not help me. I am using databases 10.2.0.5 and 11.2.0.3.
Has somebody encountered this problem too or have I missed something?
Thank you
D.drop table fkv;
CREATE TABLE fkv (
id NUMBER(1) CONSTRAINT nn_fkv_id NOT NULL,
parent_id NUMBER(1) CONSTRAINT nn_fkv_paid NOT NULL
CREATE INDEX PK_FKV_ID ON FKV(ID);
ALTER TABLE fkv ADD CONSTRAINT pk_fkv_id PRIMARY KEY (id);
ALTER TABLE FKV ADD CONSTRAINT FK_FKV_PAID FOREIGN KEY (PARENT_ID) REFERENCES FKV(ID);Now run your MERGE statement and it works with non deferrable constraints.
Personally, I would contact support about this before depending on it in production.
P.S. I was not able to reproduce your findings that dropping and re-adding the constraints changes things. I suspect that when you dropped the constraint the index was NOT dropped, so you kept a non-unique index.
Try again using ALTER TABLE FKV DROP CONSTRAINT PK_FKV_ID drop index; -
Foreign Key Constraint Failure on Self-Referencing Table
In a recent data deletion project, I ran into a problem where Oracle allowed for a record (the parent) to be deleted when there still existed a child record in the same table which referred to the parent.
An abbreviated version of the table is as follows:
create table test (
template_id number not null,
customer_id number null,
parent_id number null,
constraint pk_test primary key (template_id),
constraint r_parent foreign key (parent_id) references test (template_id));
The parent and child records are as follows:
Parent: template_id = 100, customer_id = 200, parent_id = null
Child: template_id = 101, customer_id = null, parent_id = 100
Records were deleted from this table using:
DELETE FROM test WHERE customer_id = 200;
When this statement is executed, is it being executed as part of 155 delete statements using PL/SQL, and tens of thousands of records from 155 tables are being deleted. These delete statements have been ordered taking into account foreign key constraints. All 155 statements are being deleted in a single transaction. The delete statement above was the 23rd statement of the set to be executed. I would have expected when this delete statement was executed, an error would have been thrown. However, all 155 delete statements successfully complete, and after committing the results, the child record above still exists in the DB as an orphan. I also tried executing the first 23 statements manually in SQL*Plus (still one transaction), and the problem still occurs: the parent is deleted and the child is orphaned.
If I execute the very simple example above, I do indeed get an referential constraint error.
Has anyone ever encountered this situation? And does anyone have any ideas how to go about troubleshooting this problem. We need to know the cause of this, as we have a small handful of table with a similar self-referential foreign key constraint set-up.
Thank you very much in advance,
MarkFirst of all, the very simple example that I outlined above I have already tried and it worked: when I attempted to delete the parent a referential integrity error was thrown as one would expect. This small example was my test case to see if I could reproduce what I'm seeing in our application in a more manageable and demonstrable example. But as it worked, I'm still perplexed in reconciling the differences between what I'm seeing in our application (which I can't demonstrate in this help group) and the test case. When I used the test case in my first posting in this thread, I used it to help describe the problem I'm encountered, even though that small example works.
Below is more of the table you've asked for.
OWNER CONSTRAINT_NAME CONSTRAINT_TYPE TABLE_NAME SEARCH_CONDITION R_OWNER R_CONSTRAINT_NAME DELETE_RULE STATUS DEFERRABLE DEFERRED VALIDATED GENERATED BAD RELY LAST_CHANGE INDEX_OWNER INDEX_NAME INVALID VIEW_RELATED
"DOCPADMIN" "R_TEMPLATE_PARENT" "R" "DCR_TEMPLATE" (null) "DOCPADMIN" "XPKDCR_TEMPLATE" "NO ACTION" "ENABLED" "NOT DEFERRABLE" "IMMEDIATE" "VALIDATED" "USER NAME" (null) (null) "2010-01-13 19:01:21" (null) (null) (null) (null)
"DOCPADMIN" "XPKDCR_TEMPLATE" "P" "DCR_TEMPLATE" (null) (null) (null) (null) "ENABLED" "NOT DEFERRABLE" "IMMEDIATE" "VALIDATED" "USER NAME" (null) (null) "2010-01-13 15:48:31" (null) "XPKDCR_TEMPLATE" (null) (null)Overall, I haven't said that Oracle's FK mechanism is broken. What I've said is that I've got a situation that I'm trying to understand. My first attempt at my test case didn't work because the test case worked as it should. I'm trying to figure out another course of action to try and figure this situation out. -
Deleting records from Self-Referencing Table
I am using this query to dodge the foreign key error when trying to delete a record from a table that has primary key and referencing foreign key in the same table. It works with smaller set of data but for a table with 400,000 records it fails with error
: maximum recursion limit of 500 reached. I changed maxrecursion to 3267 and even 0. but no records were returned it infact went to infinite loop..
Please help if u have an alternative solution othr than a cascade trigger(which I am already considering)
WITH q AS
SELECT id, siteUrl
FROM TestComposite
WHERE id = 42
AND siteUrl = 'site1'
UNION ALL
SELECT tc.id, tc.siteUrl
FROM q
JOIN TestComposite tc
ON tc.parentID = q.id
AND tc.siteUrl = q.siteUrl
select *
FROM TestComposite
WHERE EXISTS
SELECT id, siteUrl
INTERSECT
SELECT id, siteUrl
FROM q
Thanks,
JI am using this query to dodge the foreign key error when trying to delete a record from a table that has primary key and referencing foreign key in the same table. It works with smaller set of data but for a table with 400,000 records it fails with error
: maximum recursion limit of 500 reached. I changed maxrecursion to 3267 and even 0. but no records were returned it in fact went to infinite loop..
That is a questionable approach. Don't dodge table constraints. They have a reason to be there. Deep recursion is also doubtful approach.
USE tempdb;
GO
SELECT * INTO Employee FROM AdventureWorks.HumanResources.Employee;
GO
ALTER TABLE Employee ADD constraint PK PRIMARY KEY (EmployeeID);
ALTER TABLE Employee ADD constraint fkPK FOREIGN KEY (ManagerID) REFERENCES Employee(EmployeeID);
GO
SELECT * FROM Employee;
GO
-- Staff - no child records
DELETE Employee WHERE EmployeeID = 283; -- (1 row(s) affected)
-- Manager - child records
DELETE Employee WHERE EmployeeID = 284;
Msg 547, Level 16, State 0, Line 19
The DELETE statement conflicted with the SAME TABLE REFERENCE constraint "fkPK". The conflict occurred in database "tempdb", table "dbo.Employee", column 'ManagerID'.
The statement has been terminated.
Kalman Toth Database & OLAP Architect
SQL Server 2014 Design & Programming
New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012 -
Very long materialized view refresh when using self-referencing table
hi,
I have the following query, that takes 15 sec. to execute. When building a materialized view for it, the refreshing process doesn't stop for hours. The result of the query are about 500 rows and the tables contain not more than some 1000 rows, so it's a really simple query.
SELECT a.A,
b.B,
c.C
FROM (SELECT *
FROM (SELECT a
FROM TableA)) a,
(SELECT b
FROM TableA
WHERE type = 3) b,
(SELECT c
FROM TableA) c
WHERE TRIM (a.x) = TRIM (b.y) AND b.z = c.w;I think it has something to do with the fact, that the same table is used 3 times in the query. When I look in the trace I see that the following statement is executed:
INSERT /*+ BYPASS_RECURSIVE_CHECK */
INTO DM.Test_MV
SELECT ...What is the + BYPASS_RECURSIVE_CHECK / hint doing? Can I deactivate it somehow?
And why is there any difference between the query execution and the query execution when refreshing the mat view?
Thanks for your help!5 digit version no? lots of bugs with mviews out there.
theres a specific note (not a bug) on support 1115148.1 that references that hint though, so try dropping and recreating the view before refreshing. -
JTree, BC4J and self referenced table
Hello.
table OBJECTS which has a primary key ID and a parent ref PARENTID.
This is to have a tree structure of objects.
I want that viewed in a JTree structure (using jclient and bc4j's)
How do i do that? if i do the obvious and use the object view with itself as accessor,
The tree is fine except ALL objects are stored on the rootlevel (of course).
Is there a way to make a polymorphic restriction only on root level, or do I use two viewobjects to represent the data? (and how would i do that the right way?)
Or is there another way?
Thanks.Is there a way to make a polymorphic restriction only on root level, or do I use two viewobjects to represent the data? (and how would i do that the right way?)No you should not have to use Two different VOs. See a discussion on OTN thread:
Re: LDAP Authentication and DB user -
Select root record in hierarchic self-referencing table
Hi,
is there a quick way to select the root record from any given ID?
with t as (
select 1 as PID, null as PARENTID, 'Root 1' as DESCRIPTION from dual union all
select 2,1,'Sub 1.1' from dual union all
select 3,1,'Sub 1.2' from dual union all
select 4,null,'Root 2' from dual union all
select 5,4,'Sub 2.1' from dual union all
select 6,5,'Sub 2.11' from dual
select
from
t
where
t.PID = 6;SQL> with t as (
2 select 1 as PID, null as PARENTID, 'Root 1' as DESCRIPTION from dual union all
3 select 2,1,'Sub 1.1' from dual union all
4 select 3,1,'Sub 1.2' from dual union all
5 select 4,null,'Root 2' from dual union all
6 select 5,4,'Sub 2.1' from dual union all
7 select 6,5,'Sub 2.11' from dual
8 )
9 select pid , CONNECT_BY_ROOT pid root_node
10 from t
11 where pid = &a
12 start with parentid is null
13 connect by prior pid = parentid
14 /
Enter value for a: 6
old 11: where pid = &a
new 11: where pid = 6
PID ROOT_NODE
6 4
SQL> /
Enter value for a: 5
old 11: where pid = &a
new 11: where pid = 5
PID ROOT_NODE
5 4
SQL> /
Enter value for a: 3
old 11: where pid = &a
new 11: where pid = 3
PID ROOT_NODE
3 1
SQL> /
Enter value for a: 2
old 11: where pid = &a
new 11: where pid = 2
PID ROOT_NODE
2 1
SQL> /
Enter value for a: 1
old 11: where pid = &a
new 11: where pid = 1
PID ROOT_NODE
1 1Edited by: Karthick_Arp on Jan 20, 2009 4:39 AM -
Self referencing tree flavoured with another table
hello community,
sorry for stupid thread title, but I can't find the right description for what I want to do atm :)
I'm trying to create a tree from a self referencing table, but in addition I have to display childs with data from an aditional table (with reference to self referencing table). I'm using the latest JDeveloper (11.1.1.2.0) with internal WebLogic.
To create a "not so fictive" scenario: HR.EMPLOYEES + (new) table PROJECTS (project_id, employee_id, project_name) - I want to create a tree of all employees starting with King and in addition display the assigned projects for each employee.
It works fine without the PROJECTS table - self referencing just works as intended:
I did this by creating a "root" viewobject on EmployeesEO ("where EmployeesEO.MANAGER_ID is null"), one "standard" viewobject on EmployeesEO (EmployeesEOView) and one viewlink on EmployeesEOView linking to itself (0..1:* EmployeeId - ManagerId):
some screenshots:
[the datamodel|http://img405.imageshack.us/img405/9931/selfrefworksdatamodel.png]
[the binding rules|http://img525.imageshack.us/img525/6606/selfrefworksbinding.png]
[the browser output|http://img6.imageshack.us/img6/2906/selfrefworksbrowser.png]
Next, I created another (standard) viewobject on my (new) table "projects" and then created a new viewlink on EmployeesEOView (source) linking to my new AspProjectsEOView (destination) with cardinality 0..1:* EmployeeId - EmployeeId.
After this, I added the new created viewlink to the data model of the application module and bound the new data control to the page again (as best as I could figure out the bindings).
The result is kinda strange, I guess because ADF wants (but can't) figure out wich one to display. Well it should not display one of them, but both.
again, some screenshots:
[the datamodel|http://img297.imageshack.us/img297/6721/selfrefnotokdatamodel.png]
[the binding rules|http://img263.imageshack.us/img263/6820/selfrefnotokbinding.png]
[the browser output|http://img263.imageshack.us/img263/1720/selfrefnotokbrowser.png]
Well you may ask yourself what's my desired result: All stays the same (in this example) but the last "manager" looks like this (in expanded mode)
201 Michael Hartstein 100
____> 202 Pat Fray 201
____> Project 1
Any employee without projects should appear in the usual way (not to be filtered out), the projects should just be added.
My question is: is this even possible? If yes, how? If not, is there a way to "adjust" the output text of the "subviews" (this could be a "low tech" version - subelements named "Employees" and "Projects" instead of "EmployeesEOView" and "AspProjectsEOView")
Thanks alot in advance for any hint!
Edited by: asp_jko on 18.12.2009 17:46any help? please! :)
Maybe you are looking for
-
ITunes no longer recognizes I have already purchased apps!
First, I use Unix. I am VERY unhappy that Apple forces me to either have a Windows or MAC installation to sync iPhone. After getting my iPhone the way I wanted it, I dumped Windows completely, not realizing that I was thus deleting my iTunes app and
-
Hi Experts, When I create MIRO, the baseline date always blank. Payment terms is filled, but baseline date always blank. Everytime I try to fill manually the baseline date, when I enter. It goes back to blank. I cannot save invoice. Please help. Than
-
Can I use the iphone 5S unlocked t-mobile in Russia? Is it unlocked worlwide or only in the US?
-
J2MEWTK 1.0.2 and J2MEWTK 1.0.3
I've installed version 1.0.3 and it runs well, but I want to know if I can use other classes for version 1.0.2, because it can for version 1.0.3. Thanks.
-
Working with APEX_APPLICATION.GFXX
Hello, I have created a series of checkboxes on my page. When the page is submitted I loop through the apex_application.GF01 array to see which of check boxes has been set. FOR I in 1..APEX_APPLICATION.G_F01.COUNT LOOP update mytable set status = 'CH