如何在SQL Alchemy中结合CASE和EXISTS?

时间:2017-09-30 11:05:06

标签: python sqlalchemy

例如:

SELECT 
  CASE WHEN EXISTS (
    SELECT 
      * 
    FROM 
      "Teaching"
    WHERE 
      "Teaching".student_idn = "Student".idn
  ) THEN 'Teaching Assistant' ELSE 'Student' END AS "Category" 
FROM 
  "Student"

如何在SQL Alchemy中编写?我能够弄清楚CASE是如何完成的。但是当我们需要EXISTS

时,它变得越来越复杂

1 个答案:

答案 0 :(得分:0)

以下方法有效:

sub = session.query(Teaching).filter(Teaching.columns.student_idn == Student.columns.idn)

query = session.query(Student.columns.name, case([(sub.exists(), "Teaching Assistant")], else_ = "Student")
)

可能有更好的方法。