0

我正在开发一个广泛使用 sqlalchemy 的代码库,而且我是新手。我在为要编写的查询编写 sqlalchemy 表达式时遇到问题。

我们有以下 3 个表:

  1. 产品 -(product_id、product_description、status、available)
  2. 类别 - (category_id, category_description)
  3. ProductCategoryLink - (product_id, category_id) [对于多对多关系]

我正在运行一个查询,该查询为我提供了每个类别的产品数量。有些产品没有分配到任何类别,我也想要这些产品(在这种情况下,类别将为空)。我想出了以下查询

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)

我在这里做错了什么?

4

2 回答 2

1

当您在 Category 上加入 Category 时,它应该有一个别名。

https://stackoverflow.com/a/1435186/708221

于 2012-12-11T08:28:09.120 回答
0

关于文档中的别名:http: //docs.sqlalchemy.org/en/rel_0_9/orm/tutorial.html#using-aliases

于 2013-11-18T15:28:24.137 回答