python - SQLAlchemy 中的计数和分组依据

标签 python mysql sqlalchemy

我在 SQLAlchemy 中有这个表(数据库在 sqlite3 中):

镜头表

    shot_id    frame_id   ....
       1         10
       2         11
       3         10
       4         20
       5         20
       6         5
       7         20
       8         6
       .         .
       .         .
       .         .

在此表中,shot_idprimary 键,frame_idforeign 键。现在我想编写一个查询,为我提供所有具有相同 frame_idframe_id 数量大于或等于的 shot_id 2. 例如,在上表中,我想要 frame_id=10shot_id 1,3(它们都有相同的 frame_id 和有 2 个条目带有 frame_id=10 ) 和 shot_id 4,5,7 for frame_id=20。我写了这个查询:

根据 count(frame_id)>=2 的 frame_id 从镜头组中选择 shot_id,count(frame_id);

但它只给了我 shot_ids 3 和 7。看来 group by 只保留每个组的最后一个元素。我应该怎么做才能获得所有镜头?

最佳答案

如上所述,您不需要“计算”任何东西;自连接就足够了...

SELECT DISTINCT x.* 
           FROM my_table x 
           JOIN my_table y 
             ON y.frame_id = x.frame_id 
            AND y.shot_id <> x.shot_id;

关于python - SQLAlchemy 中的计数和分组依据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34116290/

相关文章:

python - 为 python 安装 mysqldb

mysql - 无法创建表(errno : 150)?

php - Yii 查询生成器结果(带连接和子查询的纯 SQL)

python - 在 SQLAlchemy 中使用连接

python - 在 SQLALchemy 中创建具有多态性的自引用表

python - 从包含 dict 的 pandas 列中提取有用的信息

python - 如何在虚拟机上使用 pyautogui?

python tensorflow - relu 未在自动编码器任务中学习

c# - 如何显示两个表的信息?使用内连接

未提交检测对象(例如回滚)时 SQLAlchemy 内存泄漏