简体   繁体   English

Sqlalchemy:查询 - 当所有孩子满足不平等条件时,只获得父母

[英]Sqlalchemy: Query - get only the parents when all child's satisfy the inequality condition

i am new with databases and sqlalchemy and i am trying to make a query using an inequality condition, but it always return the parent aslong as one of the childs satisfy the condition and i need all the childs satisfy that inequality 我是数据库和sqlalchemy的新手,我正在尝试使用不等式条件进行查询,但是只要其中一个孩子满足条件并且我需要所有孩子满足这个不等式,它总是返回父级。

My current tables: 我目前的表格:

class Jefe(Base):
    """ Tabla de jefes"""

    __tablename__ = 'jefe'

    id = Column(Integer, primary_key=True)
    nombre = Column(String, unique=True)
    empleado = relationship('Empleado', backref='jefe', cascade='all, delete-orphan')


class Empleado(Base):
    """ Tabla de empleados"""

    __tablename__ = 'empleado'

    id = Column(Integer, primary_key=True)
    jefe_id = Column(Integer, ForeignKey('jefe.id'), nullable=False)
    nombre = Column(String, unique=True)
    salario = Column(Float)

my actual query: 我的实际查询:

result = Session.query(Jefe).join(Empleado).filter(Empleado.salario > 120).all()

which output is: 哪个输出是:

Jefe: Yehender carrasco --- id: 1 
 ----------- Empleados
 ----------- nombre: Jesus ramirez --- salario: 150.00 --- id: 1
 ----------- nombre: Erlinda pereira --- salario: 130.00 --- id: 2


Jefe: Kleiver carrasco --- id: 2 
 ----------- Empleados
 ----------- nombre: Jesus carvajal --- salario: 155.00 --- id: 3
 ----------- nombre: Victor araujo --- salario: 135.00 --- id: 4
 ----------- nombre: Cristhiam ochoa --- salario: 105.00 --- id: 9


Jefe: Ivan marquez --- id: 4 
 ----------- Empleados
 ----------- nombre: Eliana ortega --- salario: 145.00 --- id: 7
 ----------- nombre: Sofia marquez --- salario: 133.30 --- id: 8

And I want the second result not to appear given that cristhiam ochoa's salary is less than 120, like this: 而且我希望第二个结果不会出现,因为cristhiam ochoa的薪水低于120,如下:

Jefe: Yehender carrasco --- id: 1 
 ----------- Empleados
 ----------- nombre: Jesus ramirez --- salario: 150.00 --- id: 1
 ----------- nombre: Erlinda pereira --- salario: 130.00 --- id: 2


Jefe: Ivan marquez --- id: 4 
 ----------- Empleados
 ----------- nombre: Eliana ortega --- salario: 145.00 --- id: 7
 ----------- nombre: Sofia marquez --- salario: 133.30 --- id: 8

I know that I have to modify the filtering condition so that all the children are taken into account, but I do not know how to do it 我知道我必须修改过滤条件,以便考虑所有孩子,但我不知道该怎么做

You're not setting up your join properly. 您没有正确设置加入。 Try this: 尝试这个:

result = Session.query(Jefe).join(Jefe.empleado).filter(Empleado.salario > 120).all()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM