Queries :: Recursive Table - Get All Childs For Given Parent
Feb 25, 2014
I've a table that looks something like this:
id, parentID, name
ParentId links to id.
Now I would like to get all "child-nodes" for a given parentId.
The recursion goes 4 levels deep.
What I've so far is:
Code:
SELECT t1.id, t2.id, t3.id, t4.id
FROM tblPersons AS t4
INNER JOIN (tblPersons AS t3
INNER JOIN (tblPersons AS t1
INNER JOIN tblPersons AS t2 ON t1.id = t2.parentId) ON t3.parentId = t2.id) ON t4.parentId = t3.id
WHERE (t1.id=1234);
I have a set of data in a database that has a field "parent id" (the id of another row in the database) that I want to track back to where the parent id = 0
Now there could be any number of iterations needed to get through to this result so i cant just run a query once...
I could write a vb script to do the queries and build up an array of the results, but I am wanting to access this data through crystal reports so dont think that option will work.
Ideally what I want to do is create a query that will return the list of data as a result set that I can access through crystal.
Is this possible at all?
If it is, please can someone advise how this could be done?
I have a table I'm trying to query information out of. Key fields are below:
RecNo (Key) ParentRecNo Description
I need to have a "record" in the query show both the description of itself, as well as it's parent. I was hoping to use Dlookup directly in the query design. If there is no other way, I suppose I could create a temp table and look through the recordset in VBA and dump them into the temp table, but like I said; quick and dirty was the hope here, it's for my own use, and the tables aren't large 50-100 records is what I'll be pulling out when I use this.
I have a parent table (tblLabels) and a child table (tblRevision) where the revision history for the parent table is kept.
The parent table is populated via an excel import and may have several records imported at once. Instead of having the user manually enter a new record note in the child table for each record imported into the parent table, I've created a form that collects the necessary data (date, person who added the record, person who authorized the record, and notes) and then creates a revision history for each new record.
This is what I have so far:
Code:
Private Sub cmdAddNotes_Click() Dim strSQL As String Dim RevisionDate As String Dim RevisionRevisedBy As String Dim RevisionDesc As String
[Code] ....
When I run the code nothing happens. No error, no new records create, etc. My suspicion is that I may need to use an INSERT INTO query instead of an UPDATE query, but I'm not sure how to go about matching up the foreign keys if that's the case.
Sooo, I finally have the chance to tear apart some of the horrible structures that live in one of my databases.
Currently it Tracks systems access levels across the company, and to do this we create Roles that are loosely based on the company structure and comprise of 4 constituent parts in the name and a bunch of stuff that govern the access level of accounts in that role on the system in question.
To handle this I have 4, interrelated, Tables called role 1, role 2 and so on which contain simply the descriptor of the role part that they contain, so that [Role 1] might contain "Finance", [role 2] might contain "payroll", [role 3] "contrator payments", [role 4] "payments administrator".
Role 1 is related to role2,3,4 and so on up the chain and each individual role table is related to the "master" Role definition which contains the access level information for the system in question.
I'm hoping at this point that everyone currently looks similar to :eek:
If not, let me add that A role can currently contain either [role 1],[role 2][role 3] and a placeholder "#no level 4#" or can contain a "proper" descriptor in [Role 4].
Because of the design, we currently have 3000+ "no level 4#"s held in [Role 4] (wheres the slap head smiley when you need it?)
Now I've been looking at a number of ways of trying to Normalise and improve this part of the DB, the obvious solution, because role 1-4 tables are purely descriptors is to just combine all of those into one "role" table, stick a junction table between it and the Role Definition table and be done with it. However this still leaves several problems, we're still, sort of, hardcoded to 4 levels within the database itself (ok so we can just add another column if we need more) and a few other obvious failings.
Still with me?
So I've started to look into the possiblity of using a recursive relationship on what is still, in effect, the Junction table between the descriptors and the Role Definition.
At a basic level I now have 3 tables:
Role ---- RoleID - PK Description - varchar
Roleconfig ---------- ConfigID - PK ParentconfigID - int RoleID - int
Roledefinition ------------- ID RoleconfigID
ParentconfigID relates to ConfigID within RoleConfig
At the moment, this structure, again at a basic level, now appears to work. However the variable elements within a role looked like a potential problem. Finding element one is simple, the [partentconfigID] is NULL. Finding the Top element when you've got 4 is simple, [configID] doesn't appear in [parentconfigID].
Where the fun starts is trying to control the recursion where you've got role1,role2, role3 being a valid role description and a role4 added to it also being a valid role description. Now as far as I can see there are two options to handle this.
1) Create in Roleconfig an entry (ok, entries) for role1,2,3 and use that as your 3 element role description. Create new entries containing the same information for your 1,2,3,4 role element. Less than ideal for, I hope, obvious reasons, we're still basically duplicating information and it is also difficult to build your role description in a query because you don't know how many elements will comprise that description.
2) Add a "valid" boolean column to roleconfig so that you can reuse your existing 1,2,3 and simply tag role 3 as 'valid', then add a role4 element and also tag that as 'valid'. The main downside to this is similar to the last one above, you know that valid means it is a top level description, but you still don't know how many elements there are and outputting a list containing
Finance-Payroll-ContractorPayments-PaymentAdmin AND Finance-Payroll-ContractorPayments
As valid roles still looks like it requires some jiggery-Pokery
I still have some concerns about controlling the recursion and ensuring that roledefinition can only relate back to a valid top level role which looks like it will require some careful planning. It's necessary to create a validation rule so that parentconfigID cannot be the configID for example, and I'll need to ensure that Roledefinition cannot relate to a roleconfig that isn't the last element in the chain.
We already "shoehorn" what are effectively 5+ element role descriptions into this structure, using recursion like this, I believe, eliminates the need for future Database changes if the front end code is amended to handle it. Which I guess is where the "discussion" part of the thread title comes in.
Sorry for the length of the thread, but this is melting my brain at the moment and it's not something that seems to come up very often so thought it might be interesting.
I am trying to write a product-row material cost program. Every product consists of row materials. When I sum up cost of row materials of each product I can find cost of products. But when the row material of the a product is a row material again the my solution does not work.
I have another table that has costs of row materials.
My query computes the cost of p1 but does not compute the cost of p2 since not knowing the cost of p1. I need a recursive structure that can compute cost of p2.
1. Cat NA 2. Dog NA 3. Rat NA 4. Bat NA 5. Garfield NA
table: felines 1. Cat 2. Garfield 3. Simba
what I want to do is:
UPDATE animals.field3 (which starts off as NA's) to "meow" if animals.field2 matches any item in felines.field2.
it is a recursive operation and I'm not sure how to do it
here is what the animals table should look like if the UPDATE query runs as it should
1. Cat Meow 2. Dog NA 3. Rat NA 4. Bat NA 5. Garfield Meow
Any help would be great! I prefer SQL view of the UPDATE query if anyone knows how to do this. Note: I like cats and dogs equally, this is just to learn how to do such an update.
I'm trying to create a capacity report for my database. Originally, I only had the one table, which summed the number of Packs and number of Images, worked out percentage capacity used and then put it in a report, showing for each week of the year. However since then, I've added a child table to this, allowing me to create subrecords. The reason we did this was so we could easily group together multiple mailings under one single master record, so to speak.
Going back to the capacity, I've managed to work it so the Pack capacity is worked out from the mailing quantity in the subrecord. However, the number of Images is only entered onto the Parent record. Now my capacity query is summing the same number of images as there are subrecords, where in reality I only want it to sum the Images in the main record. I know I could add an Images field to the child table and work it out the same way, but I'd rather not do that (because that's not how our business works).
So essentially the question is, how can I sum the Images from the parent table without repeating the sum and massively overexagerating the sum?
I am new to MS access. I have to delete records from the 2 tables, when the parent record gets deleted. I have a delete button in my form wherein the user deletes the particular record from the parent table.
When the delete button is pressed, the parent record gets deleted from the table. But I need to write a after delete trigger on the parent table to be able to delete the relevant records from the other two child tables, based on the current parent id.
what code should I write ? and should I locate the records in the before delete trigger and then write the code to delete the child record in after delete trigger ?
Hi I have a parent-child base table (accounts) with the following fields: - id - parentid - name every record's parentid is either 0 ( which means it is in the most upper level) or another record's id (which means it is the other record's child) different levels of records are being used. I mean some accounts are used in the most 1st level with no childs, some in the second level, ....
I need a query to list the accounts which are not parent to any othe records, regardless of what level they are defined.
Sorry this is so long but I am trying to make it as detailed as possible...
The Setup
My database is similar to the sample "Service Call" db. I have a main table called "tblTT" which has an autonumber primary key. The table also contains several foreign keys such as UserID (not an autonumber) from "tblUser", TechID (also not an autonumber) from "tblTech", etc. I have the relationships setup with "Enforced Referential Integrity" for both updating and deleting records. Each relationship has a RIGHT OUTER JOIN ("Join 3" in access) so that all records from child (tblTT) and only equal from parent (tblUser, tblTech, etc.) will be included. I have a form for nearly every table which serves different purposes but the main function of the DB is to create new Trouble Tickets (TT's), a.k.a. service calls. Therefore the main form used is my "frmTT" form in add mode. The form contains all the fields from my "tblTT" table and contains (directly) no fields from any other table (I guess indirectly it contains fields from all the parent tables...).
The Problem
When I pull up "frmTT" and try to create a new Trouble Ticket for a user that does not yet exist in the table "tblUser" I get the error "You cannot add or change a record bcause a related record is required in table 'tblUser'".
What I want is for my users (the "Techs") to be able to create a new Trouble Ticket without having to worry about populating the "tblUser" table (and other parent tables) first.
My Solution
I was going to (and unless someone can find an answer for me still will) fix this using VB script by setting up a query to check all the parent tables for the values in their corresponding fields in the form. If the query returns no results an "INSERT INTO" statement will run to populate the parents tables so that the form will save itself into the Trouble Ticket table ("tblTT").
I feel that this is a huge work around and not the proper fix. I would prefer to do this the right way both to have a correctly setup DB and for future reference. Can anyone help me with this?
here I have capture what is error actually when i make a DLOOKUP wizard.the box of wizard. there i want to make a relationship with table2. but we could see that table1 still show. yes right, it's reality making error and show message ""you can't modify the structure of table, because it is already in use by another person or process"and warning message ""Microsoft access couldn't launch the lookup wizard, or this wizard has been disabled...blabla...blaa"
on my laptop, ms access 2010 nothing happen the mattter and when i make DLOOKUP, parent table have been not seen.and make DLOOKUP Wizard is successfull.
why in my PC, when i make DLOOKUP wizard, parent table still show?what is this bug for MS access 2010?
Table 1: two columns - Child Tag and Parent Tag. Parent Tags can also be in Child Tag column. In other words, a parent can have multiple levels of children.
Table 2: one column - Backup Tag.
I'd like to have a form with a combo box, pick a Parent Tag, the search all its child tags and compare each Child Tag found with records in Table 2 to see if there is a match. Then populate all results in a tree view control.
A visual example :
Parent Tag ...Child Tag 1 - Back up tag found ......Child Tag 11 ......Child Tag 12 - Back up tag found ...Child Tag 2 ......Child Tag 21 ...Child Tag 3 ......Child Tag 31 .........Child Tag 311 - Back up tag found
I am working on a complex database, as i have to call sub tables in the parent table. but i don't know how i can create it. My database format is as below
Village name, UC Name, District, village basic information, village disasters history, village school safety plan, village DMC members, Hazard Map of the village,
After the field of District i have to call sub tables against each field with its details. How I can create it. in Hazard Map field i have to attach the map img files.
I have a parent form and a subform linked to the parent.
My client decided that he wants one of the controls from the parent form to be placed in the subForm area. The source of the control is still in the parent table but he just wants to place it in the subForm.
I am having a hell of a time doing this......
I tried to do it by changing the recordsource of the subForm by joining the Parent and Child tables so I could have access to that field in the subform.
But this is very ineffecient and I am getting new errors coming up as a result.
I have been having alot of trouble with this and just can't figure it out, I am trying to get data from a parent form into a subform so I can use it in equations. Specifically I have a DOB (Date of Birth) field on the main form, and want to have a =DateDiff("yyyy",[DOB],Date()) to find their age.
I need this in the subform because of some other information that relys on it. The way I have it right now you have to manualy put the DOB in the subform, and it can be different from the value in the main form. Could any of you tell me what I am doing wrong here?
I have a sub Report in the detail section of its parent. I need to hide the detail part of the parent if the subReport corresponding to the record has no data. Here is what iam trying to do but failing, any ideas... Private Sub Report_NoData(Cancel As Integer) Me.Parent.Section(0).Visible = False End Sub
I seem to be having a problem with acess 2003 in that when ever I set the parent/child relationships and go back to the front end the simple disappear?
Well, my newbie status in db development has reared its head. I knew from the beginning I didn't want to have cascade delete when deleting a clinic (parent) from the db. Problem is some queries in other areas need some clinic info and if the clinic is deleted, it won't be available. Right now I'm thinking that an easy way out is only allowing a delete if it has no attached records. If the clinic is no longer used, they can just write in the memo field that this clinic is no longer used. It's not a large db and there won't be hundreds of clinics so it may not be too bad. Any other suggestions?
where, in the case of a child, its ParentID contains the PersonID of its parent. In the Relataionships window I put two such tables, Family and Family_1 and I joined Family.ParentID to Family_1.PersonID. I set referential integrity, cascading updates and cascade deletes. I made a Parents form (by setting the ParentID criteria to Is Null), and added a Children subform (linking the ParentID of the subform to the PersonID of the main form).
The cascading updates works when I add a new child but when I try to delete a parent I get the error: Could not update; currently locked. Why doesn't the cascade delete work?
Scenario: Parent form: An order form (Order table) with data fields like Order ID and etc. In my Order Table, I have a revenue data field, which is a calculated field based on numbers of items in its subform (OrderDetails table). Since the profit data field is based on the items of the Order Details, for each time the user add an records in the OrderDetails table, it need to be recalculated. Currently, I used a calculated field in the query of the OrderDetails subform and bind it back to the main form, again it bind it back to the profit data field in the Order table.
With this method, everytime user add a record in the subform, the calculated field in the query will reflect the changes accordingly, but I have difficulty to force the changes in the calculated field to update the profit data field in the Order Table. I most of the events (like On Changes, On Dirty ....) on both parent and subforms, it seems does detect the changes.
I have a main form with 2 subforms. Subform 1 shows the results of query 1, subform 2 shows the results of query 2.
Query 2 uses query 1 as a starting point. Query 1 is updated with an option group on the main form. In other words, when I select an option on the main form, qdef for query 1 is updated and query 2 will also be affected.
If I select an option the subforms don’t update. If I close and reopen the main form, the subforms show the correct information so the queries are being updated but the subforms are not showing the updated information.
I’ve been trying to requery the subforms using the following code in the OptionGroup_Click() event:
I've got a parent/sub-form set up, both of which derive their data from linked tables connecting to a central database. As a result I've had to add coding to the NewRecord events to fetch the next primary keys from the database.
Unfortunately I'm finding that one loading the new record, the child form seems to be loading before the parent, ie the child form_Current event occurs before the parent form_Current event. Is this how it should be? It seems intuitive that the parent should load first.
I'm sure I can develop some cunning logic to get around this problem but I'm sure there must be a better way. Has anyone any experience of this parent/child set-up with linked, central database tables?