I need to figure out how to best query the parent / child relationship in SQL. Some of the parent fields will be data for the child. Here is an example:
ID Field1 Field2 ParentId -------------------------------------------- 1 stuff moreStuff 0 2 childStuff (from parent) 1
So, Field2 for the child will be the value of any parent. I need to figure out how to write my SQL so that when stripping Field @ entries for child would be "moreStuff". I am using SQL Server 2008. Thank you.
Assuming Field2 cannot be NULL, you can use LEFT JOIN with COALESCE:
SELECT T1.ID, T1.Field1, COALESCE(T2.Field2, T1.Field2) AS Field2, T1.ParentID FROM Table1 T1 LEFT JOIN Table1 T2 ON T1.ParentID = T2.ID
If this field2 can be NULL, replace the coalesce expression as follows:
CASE WHEN T2.Id IS NULL THEN T1.Field2 ELSE T2.Field2 END AS Field2
.
SELECT child.ID, child.Field1, parent.Field2, child.ParentID FROM MyTable child JOIN MyTable parent ON child.ParentID = parent.ID
self join :
SELECT parent.Field1, parent.Field2, child.ID FROM myTable child INNER JOIN myTable parent ON child.ParentId = parent.ID
node, , , . , ParentId null ( 0, , , ). , OUTER, INNER...
ParentId
SELECT parent.Field1, parent.Field2, child.ID FROM myTable child LEFT OUTER JOIN myTable parent ON child.ParentId = parent.ID /
, PHP/MySQL: http://articles.sitepoint.com/article/hierarchical-data-database
Source: https://habr.com/ru/post/1732029/More articles:How to run a class with an unknown number of String parameters? - javahttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1732024/how-to-assign-different-colors-to-items-in-jcombobox&usg=ALkJrhgdoNSIxRlWD9mFwDsvHW38urdtMwHow to add default value to array when child is not found in xml parsing? - objective-cSelect column when tapping embedded view - iphoneIs HttpResponse.Write different from StringWriter.Write? - c #what is the difference between truncate and delete command in SQL query - sql-servertr1 :: function WINAPI - c ++System.BadImageFormatException - Cannot Solve The Problem - 64bitmod_rewrite with subdomain and URL pattern - apacheDynamic form requirements in Django - pythonAll Articles