I currently have a table which has these columns:
id (INT)
parent_id (INT)
col0
col1
col2
As an example there are the following entries saved in this table:
1 NULL abc def NULL
2 1 test NULL NULL
3 1 NULL NULL xyz
Now I’d like to search in all rows A which haven’t got any rows B which are pointing to them (B.parent_id = A.id). In addition the row values should be either the ones that are present in the current row or if there is a NULL, the values of the parent should be considered.
To illustrate my requirements I’d like to show some examples:
SEARCH(col0=test) => #2 (#1 has some children, #3.col0 = abc (inherited from #1))
SEARCH(col1=def) => #2, #3 (#1 has some children)
SEARCH(col2=xyz) => #3 (#1 has some children, #2.col2 = NULL (inherited from #1))
Does anyone know how to implement such a search in MySQL?
Fast? No. Best index use you can get out of this are the joins on id/parent_id.
If you have a lot of data and small result sets, you can query the columns directly on an index and then run checks for parents and children in separate queries. That’d be a lot faster than running the above query on a huge table.