我有一个域列表和一个子域列表。例如:
域A具有子域a1,a2,a3。
域B具有子域b1,b2,b3。
域C没有子域
我需要创建数据库结构,以便可以这样进行排序:
A
a1
a2
a3
B
b1
C
我需要清楚地看到哪个是哪个域的域或子域。
我试图使用ForeignKey到域将域放在一个表中,将子域放在另一表中。
class Domain(Base):
__tablename__ = "domains"
domain_id = Column(Integer(), primary_key=True)
name = Column(String(), unique=True)
class Subdomain(Base):
__tablename__ = "subdomains"
subdomain_id = Column(Integer(), primary_key=True)
name = Column(String(), unique=True)
domain_id = Column(Integer, ForeignKey('domains.domain_id'))
我正在使用此表中的域和子域来创建第三张表:
class Title(Base):
__tablename__ = "titles"
title_id = Column(Integer(), primary_key=True)
domain_id = Column(Integer, ForeignKey('domains.domain_id'))
subdomain_id = Column(Integer, ForeignKey('subdomains.subdomain_id')) -- NULL if that is a Domain
title = Column(String())
status = Column(Integer())
答案 0 :(得分:0)
您要的是数据模型和SQL查询。
您可以使用两个表:
使用此查询:
select name
from
(
select name, name as domain_name, 'domain' as type
from domain
union all
select sd.name, d.name as domain_name, 'subdomain' as type
from domain d
join subdomain sd on sd.domain_id = d.domain_id
)
order by domain_name, type, name;
或者只有一张桌子:
使用此查询:
select name
from
(
select name, name as domain_name, 'domain' as type
from domain
where parent_domain_id is null
union all
select sd.name, d.name as domain_name, 'subdomain' as type
from domain d
join domain sd on sd.parent_domain_id = d.domain_id
)
order by domain_name, type, name;