使用 HQL 的递归查询
我有这个表
CREATE TABLE IF NOT EXISTS `branch` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`studcount` int(11) DEFAULT NULL,
`username` varchar(64) NOT NULL,
`branch_fk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FKADAF25A2A445F1AF` (`branch_fk`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=14 ;
ALTER TABLE `branch`
ADD CONSTRAINT `FKADAF25A24CEE7BFF` FOREIGN KEY (`login_fk`) REFERENCES `login` (`id`);
,您可以看到每个表都有一个指向其他分支行的外键(自关系) 我想要使用 HQL(首选 HQL)的查询从我这里获取用户名(或 id)并返回 List
(对于用户名)或 List
(对于 id)这是我所有支行的列表;
让我在示例中显示,
id studentcount username branch_fk
1 312 user01 NULL
2 111 user02 1
3 432 user03 1
4 543 user04 2
5 433 user05 3
6 312 user06 5
7 312 user06 2
8 312 user06 7
当我调用 GetSubBranch(3) 时,我想要返回:
5, 6
当调用 GetSubBranch(2) 时,我想要返回:
4, 7, 8
I have this Table
CREATE TABLE IF NOT EXISTS `branch` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`studcount` int(11) DEFAULT NULL,
`username` varchar(64) NOT NULL,
`branch_fk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FKADAF25A2A445F1AF` (`branch_fk`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=14 ;
ALTER TABLE `branch`
ADD CONSTRAINT `FKADAF25A24CEE7BFF` FOREIGN KEY (`login_fk`) REFERENCES `login` (`id`);
as you can see each table has a foreign key that point to other Branch Row (self Relation)
I want a Query using HQL(prefer HQL) to get a username (or id) from me and return a List<String>
(for username) or List<Integer>
(for id) that was a list of all of my subBranch;
let me show in Example
id studentcount username branch_fk
1 312 user01 NULL
2 111 user02 1
3 432 user03 1
4 543 user04 2
5 433 user05 3
6 312 user06 5
7 312 user06 2
8 312 user06 7
when I call GetSubBranch(3) I want return:
5, 6
and when call GetSubBranch(2) I want return:
4, 7, 8
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
人们可以看一下“嵌套集”。 查询变成了“在:L 和:R 之间”的问题。 但是拓扑/分层排序丢失了(与递归/分层查询相比)。 插入新项目的成本相当高,因为它需要更新几行(如果不是全部行)......
One may have a look at 'nested sets'. Querying becomes a matter of 'between :L and :R'. But topological/hierarchical sort is lost (in comparison to recursive/hierarchical queries). Inserting new items then is quite costly as it requires updates on several if not all rows ...
我相信没有可移植的 SQL 可以做到这一点。
更重要的是,我认为几个主要数据库的SQL都无法表达这一点。
因此,此功能不属于您在 HQL 中可以执行的操作。 抱歉:-(
我读了几种方法。大多数都涉及根据级别数量(提前固定?多少?)、记录数量(数百?数百万?)等进行权衡:
in(ids)
),直到某个级别为空。使用I believe there is no portable SQL to do this.
Even more, I think several major databases' SQL cannot express this.
Therefore, this capability is not part of what you can do in HQL. Sorry :-(
I read a few ways to go. Most of them involve tradeoffs depending of the number of levels (fixed in advance ? how many ?) , the number of records (hundreds ? millions ?) etc :
in(ids)
), until some level is empty.