Question

I'd like to use the Path Enumeration hierarchical model in my DB schema. The problem is that MySQL doesn't allow me to have a subquery on the same table to retrieve the parent row path.

Is there any way to work around this problem without creating a temporary table?

Here is the DDL for my table:

CREATE TABLE COC_FIELD
(
    field_id VARCHAR(255) PRIMARY KEY NOT NULL,
    name VARCHAR(255),
    query_id VARCHAR(255) NOT NULL,
    path_enumeration VARCHAR(1000),
    FOREIGN KEY ( report_query_id ) REFERENCES COC_QUERY ( query_id )
);

Statement to insert a child row (not allowed in MySQL):

insert into COC_FIELD(field_id, name, report_query_id, path_enumeration)
values('field_2', 'Month', 'query_1', CONCAT(
    (select path_enumeration from COC_FIELD where field_id = 'field_2'),
    '/', 'field_3'))
Was it helpful?

Solution

Will using variables be an option for you?

SET @path = (SELECT path_enumeration FROM COC_FIELD WHERE field_id = 'field_2');

INSERT INTO COC_FIELD(field_id, name, path_enumeration)
VALUES ('field_2', 'Month', CONCAT(IFNULL(@path, ''), '/', 'field_3'));

First statement sets a variable named path which will then be used in the insert statement. I used an additional IFNULL check to prevent getting null values if @path is null.

Please note that I had to remove report_query_id field for my tests.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top