在mysql中连接任意行的字符串(分层查询)
我有一个带有专辑的 mysql 表。 每个专辑可以是顶级专辑,也可以是另一个专辑的子专辑。 每个相册都有一个文件夹名称,它是其图片所在的文件夹的名称。每个相册还有一个名为“parent”的字段,它是父相册的 ID。 所以,如果我有一个像这样的图像路径:
root/album1/album2/image1.jpg
那么数据库中的专辑表将如下所示:
id parent foldername
1 NULL root
2 1 album1
3 2 album2
那么问题是,如何仅使用 mysql 从该表中获取之前打印的路径?
I have a mysql table with albums. Each album can be a top level album, or a child album of another album. Each album has a foldername which is the name of the folder its pictures are in. Each album also has a field called parent which is the id of the parent album. So, if I have a path to an image like this:
root/album1/album2/image1.jpg
then the album table in the database will look like this:
id parent foldername
1 NULL root
2 1 album1
3 2 album2
The question is then, how do I get the path printed earlier from this table with only mysql?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不确定在数据库中存储一棵树是一个好主意...
为了让您的问题简单,也许只需将专辑的完整路径存储在表的一列中...
I'm not sure storing a tree in Database is a good idea...
To keep your problem simple maybe just store the full path of an album in a column of your table...
完全未经测试,是我凭空想象出来的……
这至少应该让您知道如何获取路径名。 您从未指定文件名的存储位置。
顺便说一句,这会很慢。 我讨厌使用光标...
Totally untested and typed off the top of my head...
That should at least give you an idea how to get your path names. You never specified where your file names were stored.
BTW, this is gonna be slow. I hate using cursors...
DB2、SQL Server、PostgreSQL 和 Oracle 都支持通用表表达式 (CTE),可用于完成此任务。 Oracle 还有“CONNECT BY”关键字。
我知道这并不能解决你的问题,但也许它会帮助其他人寻找 MySQL 以外的解决方案。
在您的情况下,出于性能考虑,我建议将完整路径存储在列中 - 插入/更新时对非规范化数据的管理可能会在读取性能方面获得很多倍的回报。
DB2, SQL Server, PostgreSQL, and Oracle all support Common Table Expressions (CTE), which can be used to accomplish this. Oracle also has the "CONNECT BY" keyword.
I know that doesn't solve your problem, but maybe it will help someone else looking for a solution on something other than MySQL.
In your case, for performance sake, I recommend storing the full path in a column--the management of the denormalized data on insert/update will likely pay itself back many times in performance on reads.