我有一个自引用表,如下所示:
class Domain(Base):
__tablename__ = "domains"
domain_id = Column(Integer(), primary_key=True)
parent_id = Column(Integer(), ForeignKey('domains.domain_id'))
domain_name = Column(String(255), unique=True)
数据示例:
domain_id,parent_id,域名
1,,google.com
2,,yahoo.com
3,1,images.google.com
4,1,drive.google.com
5,2,mail.yahoo.com
我需要编写一个查询,其中所有域都将放置在其父域之后。
1,,google.com
3,1,images.google.com
4,1,drive.google.com
2,,yahoo.com
5,2,mail.yahoo.com
我最好的尝试是:
subdomain = aliased(Domain, name='subdomain')
domains = session.query(Domain, subdomain.domain_name)
domains = domains.outerjoin(subdomain, Domain.parent_id==subdomain.domain_id).filter_by(domain_name=None)
subdomains = session.query(Domain, subdomain.domain_name)
subdomains = subdomains.join(subdomain, Domain.domain_id==subdomain.parent_id)
query = domains.union(subdomains)
但是结果并不完全是我想要的结果。
1,,google.com
1,3,images.google.com
1,4,drive.google.com
2,,yahoo.com
2,5,mail.yahoo.com
domain_id和parent_id颠倒了。