I've got a table structure like (simplified):
content
- id_content
- my_string1
- ...
content_has_content
- id_content
- id_subcontent
topic_has_content
- id_topic
- id_content
Any topic can have multiple 'content', any 'content' can have multiple 'subcontent' (instance of content). With a given id_topic I'd like to recieve a list of all my_string1 from the linked contents, subcontents, subcontents-of-subcontents, and so on.
I understand "WITH" is not working for mysql but cannot find a nice recursive alternative.
Thanks daniel
There is no recursion in MySQL and also the result you would get would be flat (no structure). The best way is still a while loop in PHP, Java or whatever programming language you use.
The query could look like this:
and in PHP you could repeat the query with the next sub_content_id, until
ID_SUBCONTENT is null
Solution
PosgreSQL, Oracle, MS-SQL, ... have
WITH RECURSIVE
to handle such data structures. It internally uses a while loop to get all theparent ids
for the current row (we need the child's here instead)This can achieved in
MySQL
too, you can create astored procedure
and reproduce the same behaviorAssumed/DDL used
content_has_content
has entries asI pass the
id_content
as 2 and get the output asAll of the above are descendants of
content_2
Fire
call content_details(2);
to get all the child rows for the passedid_content
SQL
What I basically do is run a
while loop
until I have the lastchild_id
, store theseids
in acomma separated string format
and then fire a query to get all the rows which have aid
present in thevar
I just createdNote: There are chances you could be having invalid values within your tables, such as row having a
id_subcontent
, which points to its ownid_content
, which could cause a never endingloop
within the procedure, to avoid such situations, you can use a counter and limit the nesting to say around 50 (or any value as per your requirement) andraise a exception
if that limit is surpassedSome data to play with..
Hope this helps..