0

我有一张有学生信息的表格,现在我想知道男女学生的人数。使用普通 SQL 我可以使用它

select student_gender, count(student_gender) from student_registration group by student_gender;

经过一番小搜索,我在 SQLAlchemy 中发现了以下等价性

gender = db.session.query(Student_Registration.student_gender, \
                        func.count(Student_Registration.student_gender))\
    .group_by(Student_Registration.student_gender).all()

现在我想打印所需的输出。使用

for b in gender:
    print(b.student_gender)

如何打印计数?我试过 b.count 但它显示

Female <built-in method count of result object at 0x7fac60f21240>
Male <built-in method count of result object at 0x7fac60f21288>
4

2 回答 2

0

您已经创建了查询,现在您必须执行它并检索结果(是的,当我第一次开始时它也让我感到困惑)。为此,请使用您所拥有的并添加以下内容...

假设您还没有与数据库的连接(您实际上可能已经有了 - 为您的连接替换正确的参数 - 数据库连接字符串、uid、pw ...)...

qry_engine = create_engine('mysql+pymysql://uid:pw@localhost:3306/charset=utf8mb4',
                           pool_recycle=3600, echo=False)

然后添加如下内容

rslt = qry_engine.execute(gender).fetchall()
for rslt_row in rslt:
    print(str(rslt_row))

我实际上并没有运行这些命令,所以我可能稍微搞砸了语法,但解释器应该告诉你我在哪里犯了错误(让我知道,我会修改我的答案)。希望能帮助到你!

于 2020-07-06T17:21:33.913 回答
0

您可以使用标签

gender = db.session.query(Student_Registration.student_gender, \
                        func.count(Student_Registration.student_gender).label('count'))\
    .group_by(Student_Registration.student_gender).all()

for b in gender:
    print(b.student_gender, b.count)
于 2020-07-06T18:19:32.403 回答