【问题标题】:SQLAlchemy Get All Rows For Column CombinationSQLAlchemy 获取列组合的所有行
【发布时间】:2020-09-23 12:24:40
【问题描述】:

我正在使用 Flask-SQLAlchemy(但如果需要,我愿意使用 SQLAlchemy)并试图找出一种方法来从一个表中获取所有值,其中 4 列的组合是唯一的。

例如,我有这个对象类 -

class SearchRule(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  type = db.Column(db.Text)
  location = db.Column(db.Text)
  owner = db.Column(db.Text)
  delegate = db.Column(db.Text)
  set_id = db.Column(db.Integer, db.ForeignKey('set.id'))

我想要返回的是所有 set_id 值,其中 type + location + owner + delegate 的组合是唯一的。

这是一个示例表 -

id    type    location    owner    delegate    set_id
1     db      usa         matt     joe         5
2     db      usa         matt     joe         6
3     db      uk          jim      bob         9
4     db      uk          jim      bob         12

我想从这张表中返回如下内容 -

[
  ('db', 'usa', 'matt', 'joe', [5, 6]), 
  ('db', 'uk, 'jim', 'bob', [9, 12])
]

Any help would be greatly appreciated!

【问题讨论】:

    标签: python sqlalchemy flask-sqlalchemy


    【解决方案1】:

    为什么不能在这里工作。 Group by 将通过什么是分组为您提供不同的列值,然后将 distinct 应用于聚合列将为您提供不同的 id 值。如果您想要所有 id 值,只需省略 distinct()

    
    from sqlalchemy.sql import func
    
    query = session.query.(SearchRule.type, SearchRule.location,
                               SearchRule.owner, SearchRule.delegate, 
                               func.group_concat(SearchRule.set_id.distinct())/
                   .group_by(SearchRule.type, SearchRule.location,
                             SearchRule.owner, SearchRule.delegate)
    

    group_concat 将生成一个逗号连接的字符串,您应该能够将其转换为 Python 代码中所需的任何内容

    【讨论】:

      【解决方案2】:

      您需要运行的查询是:

      session.query(SearchRule.type, SearchRule.location, 
                    SearchRule.owner, SearchRule.delegate).distinct() 
      

      这个查询你的数据的结果是:

      ('db', 'usa', 'matt', 'joe')
      ('db', 'uk', 'jim', 'bob')
      

      要获取set-ids列表,需要使用group-concat:

      session.query(SearchRule.type, SearchRule.location, 
                  SearchRule.owner, SearchRule.delegate, func.group_concat(SearchRule.set_id)).group_by(SearchRule.type, 
                  SearchRule.location, SearchRule.owner, SearchRule.delegate)
      

      结果是:

      ('db', 'uk', 'jim', 'bob', '9,12')
      ('db', 'usa', 'matt', 'joe', '5,6')
      

      【讨论】:

      • 这也是我所知道的,但是有没有办法在结果中包含与该 4 列组合匹配的 set_id 列表?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-08
      相关资源
      最近更新 更多