"select pck.id, pck.name, deb.last_time from (select id, name from dp_package where name like %s limit %s, %s) as pck left join (select package_id, last_time from dp_deb where id in (select max (id) from dp_deb group by package_id)) as deb on pck.id = deb.package_id" %(keyword, start, limit)
问问题
66 次
1 回答
2
假设模型已定义: Base = declarative_base()
class Package(Base):
__tablename__ = 'db_package'
id = Column(Integer, primary_key=True)
name = Column(String)
def __init__(self, name):
self.name = name
class Deb(Base):
__tablename__ = 'db_deb'
id = Column(Integer, primary_key=True)
package_id = Column(Integer, ForeignKey('db_package.id'))
name = Column(String)
last_time = Column(DateTime)
def __init__(self, name, last_time):
self.name = name
self.last_time = last_time
packages = relationship(Package, backref="debs")
下面的代码应该产生相同的结果(尽管SQL
查询不同,其中一个subquery
被替换为 simple LEFT OUTER JOIN
):
# query parameters
keyword, start, limit = 'xxx', 1, 3
# subquery for the last_time
sq2h = session.query(Deb.package_id, func.max(Deb.id).label("max_id")).group_by(Deb.id).subquery("max_deb")
sq2 = (session.query(Deb.package_id, Deb.last_time).
join(sq2h, Deb.id == sq2h.c.max_id))
sq2 = sq2.subquery("deb")
qry = (session.query(Package.id, Package.name, sq2.c.last_time).
outerjoin(sq2, sq2.c.package_id == Package.id).
filter(Package.name.contains(keyword))
)[start:(start + limit)]
print qry
SQL
为SQLite
:_
SELECT db_package.id AS db_package_id,
db_package.name AS db_package_name,
deb.last_time AS deb_last_time
FROM db_package
LEFT OUTER JOIN(SELECT db_deb.package_id AS package_id, db_deb.last_time AS last_time
FROM db_deb
JOIN (SELECT db_deb.package_id AS package_id,
max(db_deb.id) AS max_id
FROM db_deb
GROUP BY db_deb.id
) AS max_deb
ON db_deb.id = max_deb.max_id
) AS deb
ON deb.package_id = db_package.id
WHERE db_package.name LIKE '%%' || ? || '%%'
LIMIT ? OFFSET ?
('xxx', 3, 1)
于 2012-12-25T17:33:37.477 回答