SQLAlchemy - in_子句中的子查询

时间:2014-11-26 22:33:19

标签: sql sqlalchemy

我如何将其转换为SQLAlchemy:

SELECT DISTINCT pa.id_product 
FROM ns_product_attribute_combination pac 
  inner join ns_product_attribute pa 
  ON pa.id_product_attribute = pac.id_product_attribute
WHERE (pac.id_attribute=25 OR pac.id_attribute=6) 
  AND pa.id_product IN 
    (SELECT pa1.id_product 
     FROM ns_product_attribute_combination pac1 
       INNER JOIN ns_product_attribute pa1 
       ON pa1.id_product_attribute = pac1.id_product_attribute
     WHERE pac1.id_attribute <> pac.id_attribute 
       AND (pac1.id_attribute=25 OR pac1.id_attribute=6)))

它包含对子查询中父查询的引用,我该如何得到它?

1 个答案:

答案 0 :(得分:0)

这非常简单;假设你有类似的东西:

from sqlalchemy import Column, Integer
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class NPAC(Base):
    __tablename__ = "ns_product_attribute_combination"
    id_ = Column(Integer(), primary_key=True)
    id_attribute = Column(Integer())
    id_product_attribute = Column(Integer())

class NPA(Base):
    __tablename__ = "ns_product_attribute"
    id_ = Column(Integer(), primary_key=True)
    id_product = Column(Integer())
    id_product_attribute = Column(Integer())

以常规方式构建查询很简单:

>>> from sqlalchemy.orm import aliased, Query
>>> pac = aliased(NPAC, name="pac")
>>> pac1 = aliased(NPAC, name="pac1")
>>> pa = aliased(NPA, name="pa")
>>> pa1 = aliased(NPA, name="pa1")
>>> innerQuery = (Query(pa1.id_product)
...         .select_from(pac1)
...         .join((pa1, pac1.id_product_attribute == pa1.id_product_attribute))
...         .filter(pac1.id_attribute != pac.id_attribute)
...         .filter((pac1.id_attribute == 25) | (pac1.id_attribute == 6))
... )
>>> print (Query(pa.id_product)
...         .select_from(pac)
...         .join((pa, pac.id_product_attribute == pa.id_product_attribute))
...         .filter((pac.id_attribute == 25) | (pac.id_attribute == 6))
...         .filter(pa.id_product.in_(innerQuery))
... )
SELECT pa.id_product AS pa_id_product 
FROM ns_product_attribute_combination AS pac JOIN ns_product_attribute AS pa ON pac.id_product_attribute = pa.id_product_attribute 
WHERE (pac.id_attribute = :id_attribute_1 OR pac.id_attribute = :id_attribute_2) AND pa.id_product IN (SELECT pa1.id_product AS pa1_id_product 
FROM ns_product_attribute_combination AS pac1 JOIN ns_product_attribute AS pa1 ON pac1.id_product_attribute = pa1.id_product_attribute 
WHERE pac1.id_attribute != pac.id_attribute AND (pac1.id_attribute = :id_attribute_3 OR pac1.id_attribute = :id_attribute_4))