Hierarchical tagging in SQL

后端 未结 5 1913
天涯浪人
天涯浪人 2020-12-25 08:59

I have a PHP web application which uses a MySQL database for object tagging, in which I\'ve used the tag structure accepted as the answer to this SO question.

I\'d l

5条回答
  •  不思量自难忘°
    2020-12-25 09:32

    I implemented it using two columns. I simplify it here a little, because I had to keep the tag name in a separate field/table because I had to localize it for different languages:

    • tag
    • path

    Look at these rows for example:

    tag            path
    ---            ----
    database       database/
    mysql          database/mysql/
    mysql4         database/mysql/mysql4/
    mysql4-1       database/mysql/mysql4-1/
    oracle         database/oracle/
    sqlserver      database/sqlserver/
    sqlserver2005  database/sqlserver/sqlserver2005/
    sqlserver2005  database/sqlserver/sqlserver2008/
    

    etc.

    Using the like operator on the path field you can easily get all needed tag rows:

    SELECT * FROM tags WHERE path LIKE 'database/%'
    

    There are some implementation details like when you move a node in the hierarchy you have to change all children too etc., but it's not hard.

    Also make sure that the length of your path is long enough - in my case I used not the tag name for the path, but another field to make sure that I don't get too long paths.

提交回复
热议问题