Python sql炼金术sql组合
我正在开发一个广泛使用sqlalchemy的代码库,我对它还不熟悉。我在为要编写的查询编写sqlalchemy表达式时遇到问题 我们有以下3个表:Python sql炼金术sql组合,python,orm,sqlalchemy,Python,Orm,Sqlalchemy,我正在开发一个广泛使用sqlalchemy的代码库,我对它还不熟悉。我在为要编写的查询编写sqlalchemy表达式时遇到问题 我们有以下3个表: 产品-(产品id、产品描述、状态、可用) 类别-(类别id,类别描述) ProductCategoryLink-(product_id,category_id)[用于多对多关系] 我正在运行一个查询,该查询为我提供了每个类别的产品计数。有些产品没有分配到任何类别,我也需要这些产品(在这种情况下,类别将为空)。我提出了以下问题 select c.cat
select c.category_name, count(p.product_id)
from Product as p
left join ProductCategoryLink as pc
on p.product_id = pc.product_id
left join Category as c
on c.category_id = pc.category_id
where p.store_id = 1111
and p.status = 'ACTIVE'
and p.available = 1
group by c.category_name;
我的orm文件中有以下映射
class Product(Base):
__tablename__ = 'Product'
product_id = Column(Integer, primary_key=True, name='product_id')
product_description = Column(UnicodeText, name='description')
available = Column(Boolean, name='available')
status = Column(Unicode(length=255), name='status')
metadata = Base.metadata
# association table between product and category
product_category_link = Table('ProductCategoryLink', metadata,
Column('product_id', Integer, ForeignKey('Product.product_id')),
Column('category_id', Integer, ForeignKey('Category.category_id'))
)
class Category(Base):
__tablename__ = 'Category'
category_id = Column(Integer, primary_key=True, name='category_id')
category_name = Column(Unicode(length=255), name='category_name')
products = relation('Product', secondary=product_category_link, backref='categories')
我想出了下面的ORM表达式
query = session.query(Category.category_name, func.count(Product.product_id)).join(product_category_link).\
join(Category).filter(
and_(Product.store_id == self._store_id,
and_(Product.status == 'ACTIVE', Product.available == 1))).\
group_by(Category.category_name).all()
上面表达式创建的sql查询不是我想要的
sqlalchemy.exc.OperationalError: (OperationalError) (1066, "Not unique table/alias: 'Category'") 'SELECT `Category`.category_name AS `Category_category_name`, count(`Product`.product_id) AS count_1 \nFROM `Product`, `Category` INNER JOIN `ProductCategoryLink` ON `Category`.category_id = `ProductCategoryLink`.category_id INNER JOIN `Category` ON `Category`.category_id = `ProductCategoryLink`.category_id \nWHERE `Product`.store_id = %s AND `Product`.status = %s AND `Product`.available = %s GROUP BY `Category`.category_name' (1, 'ACTIVE', 1)
我在这里做错了什么?当您加入Category上的Category时,它应该有一个别名
请参见文档中关于alias的内容: