无法在SQLAlchemy上使用显式连接序列(包括别名表)进行查询

时间:2012-03-06 07:00:02

标签: join sqlalchemy alias explicit

我在两个表之间进行SQLAlchemy查询时遇到了麻烦:

ProcessedDataset
    - ID 
ProcDSParent
    - ThisDataset (foreign key to ProcessedDataset.ID)
    - ItsParent   (foreign key to ProcessedDataset.ID)

要查找Parent的{​​{1}}和Child,我需要明确 指定以下之间的连接顺序: Dataset< - ProcessedDataset - > ProcDSParent

为它们制作不同的别名后,我尝试了不同的连接方法, 但仍然无法得到它。

使用ProcessedDataset的找到Parent进行演示:

Dataset

  • 方法< 1>:

FromClause.join + expression.select

dataset = DB.db_tables[db_alias]['ProcessedDataset']
dsparent = DB.db_tables[db_alias]['ProcDSParent']

parent = dataset.alias('ProcessedDataset_ItsParent')
child_parent = dsparent.alias('ThisDataset_ItsParent')

keylist = [parent.c.Name]
whereclause = dataset.c.Name.op('=')('Test')

  • 方法< 2>:

orm.join + expression.select

r_join = dataset
r_join.join(child_parent, dataset.c.ID == child_parent.c.ThisDataset)
r_join.join(parent, child_parent.c.ItsParent == parent.c.ID)

query = select(keylist, from_obj=r_join, whereclause=whereclause)

print query
SELECT `ProcessedDataset_ItsParent`.`Name`
FROM `ProcessedDataset` AS `ProcessedDataset_ItsParent`, `ProcessedDataset`
WHERE `ProcessedDataset`.`Name` = %s

正如您所看到的,它们都不是join2 = join(dataset, child_parent, dataset.c.ID == child_parent.c.ThisDataset) join2.join(dsparent, child_parent.c.ItsParent == parent.c.ID) print query SELECT `ProcessedDataset_ItsParent`.`Name` FROM `ProcessedDataset` AS `ProcessedDataset_ItsParent`, `ProcessedDataset` INNER JOIN `ProcDSParent` AS `ThisDataset_ItsParent` ON `ProcessedDataset`.`ID` = `ThisDataset_ItsParent`.`ThisDataset` WHERE `ProcessedDataset`.`Name` = %s 的{​​{1}},应该是:

Parent

感谢任何帮助,已经在这里坚持了几天!

附加最小的DDL和python代码

Dataset

(ds0,ds2) - > ds1 - > ds3 - > ds4

(ds5,ds7) - > DS6

SELECT `ProcessedDataset_ItsParent`.`Name`
FROM `ProcessedDataset` 
   INNER JOIN `ProcDSParent` AS `ThisDataset_ItsParent` ON  
          `ProcessedDataset`.`ID` = `ThisDataset_ItsParent`.`ThisDataset`
   INNER JOIN `ProcessedDataset` AS `ProcessedDataset_ItsParent` ON
          `ThisDataset_ItsParent`.'ItsParent` = `ProcessedDataset_ItsParent`.`ID`
WHERE `ProcessedDataset`.`Name` = %s

1 个答案:

答案 0 :(得分:0)

Michael Bayer通过邮件回复了我。

join()方法返回一个新的Join对象,即表示连接的对象。原始对象保持不变:

r_join = dataset
r_join = r_join.join(child_parent, ...)
r_join = r_join.join(parent, ...)

我还尝试了orm.join

join1 = join(child_parent, dataset, child_parent.c.ThisDataset == dataset.c.ID)
join2 = parent.join(join1, parent.c.ID == child_parent.c.ItsParent)