【问题标题】:SQLAlchemy - Filter query, exclude parent where one of many children meet criteriaSQLAlchemy - 过滤查询,排除许多孩子之一符合条件的父母
【发布时间】:2015-08-19 08:09:08
【问题描述】:

我的 SQL 技能相当欠缺,所以我不知道如何形成我需要的查询。

我有两个具有一对多关系的数据库模型,定义如下:

class Parent(db.Model):
  __tablename__ = 'parent'

  id = db.Column(db.Integer, primary_key = True)

  children = db.relationship('Child', 
                             backref = 'parent', 
                             lazy = 'joined')

class Child(db.Model):
  __tablename__ = 'child'

  id = db.Column(db.Integer, primary_key = True)
  parent_id = db.Column(db.Integer, db.ForeignKey('parent.id'))

  value = db.Column(db.String(140))

我希望能够形成一个查询,该查询将返回满足三个条件的所有父母:

1:有一个或多个值包含'value1'的孩子

2:有一个或多个值包含'value2'的孩子

3: 没有值包含'value3'或'value4'的孩子

对于这个示例数据:

Parents:
id |
1  |
2  |
3  |
4  |

Children:
id | parent_id | value
1  | 1         | 'value1'
2  | 1         | 'value2'
3  | 1         | 'value3'
4  | 1         | 'value5'

5  | 2         | 'value1'
6  | 2         | 'value2'
7  | 2         | 'value4'
8  | 2         | 'value5'

9  | 3         | 'value1'
10 | 3         | 'value2'
11 | 3         | 'value5'
12 | 3         | 'value6'

13 | 4         | 'value1'
14 | 4         | 'value7'

我只希望返回父级 #3。

据我所知:

from sqlalchemy import not_, and_

conditions = []

conditions.append(Parent.children.any(Child.value.ilike('%'+value1+'%'))
conditions.append(Parent.children.any(Child.value.ilike('%'+value2+'%'))

conditions.append(Parent.children.any(not_(Child.value.ilike('%'+value3+'%')))

condition = and_(*conditions)

q = db.session.query(Parent).filter(condition)

前两个条件可以正常工作。将关系设置为 lazy='join' 允许我在关系上调用 .any() 并获得我想要的结果。

但是,条件 3 无法正常工作。它会返回有一个孩子不符合标准的父母,而不是让所有孩子都不符合标准。

我已经搞砸了外部联接和其他执行此查询的方法,但我意识到我对 SQL 了解得不够多,无法确定前进的方向。谁能指出我正确的方向?只要知道我需要生成的 SQL 将是朝着正确方向迈出的一大步,但让它在 SQLAlchemy 中工作会很棒。

【问题讨论】:

    标签: python sqlalchemy flask-sqlalchemy


    【解决方案1】:

    下面的查询应该这样做:

    q = (session.query(Parent)
         .filter(Parent.children.any(Child.value.ilike('%{}%'.format(value1))))
         .filter(Parent.children.any(Child.value.ilike('%{}%'.format(value2))))
         .filter(~Parent.children.any(
             db.or_(Child.value.ilike('%{}%'.format(value3)),
                    Child.value.ilike('%{}%'.format(value4)),
                    )
         ))
    )
    

    几点:

    • 条件 3 需要 or
    • 您还应该使用NOT has any children...(使用~ 完成)或您内部的not

    条件 3 的过滤器应该是:没有任何满足 bla-bla 的孩子的父母,而您的代码暗示 至少有一个不满足的孩子的父母bla-bla.

    【讨论】:

    • 谢谢,效果很好。现在看起来很明显,但我就是想不通。
    猜你喜欢
    • 2021-08-24
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多