SqlAlchemy Core and bare exists query

前端 未结 1 1421
清歌不尽
清歌不尽 2021-01-01 00:14

I have faced a problem where I have to find if the data exists in the table using SqlAlchemy Core.

I think the best way to do this query is to use <

相关标签:
1条回答
  • 2021-01-01 00:36

    According to the documentation, exists applies to a Select object, and the following examples are provided:

    # use on an existing select()
    s = select([table.c.col1]).where(table.c.col2==5)
    s = exists(s)
    
    # construct a select() at once
    exists(['*'], **select_arguments).where(criterion)
    
    # columns argument is optional, generates "EXISTS (SELECT *)"
    # by default.
    exists().where(table.c.col2==5)
    

    What is going wrong with your code then?

    Well, from my understanding, EXISTS is not a directive by itself, so trying to execute an exists() will fail as it is not an executable clause.

    To illustrate, you can try with a simple sqlite console:

    • EXISTS(SELECT * from t); is an error
    • SELECT EXISTS(SELECT * FROM t); yields 0 or 1 as expected.

    How to fix your issue?

    Wrap your exists() in a select() executable statement:

    result = conn.execute(select([exists().where(cookie_table.c.cookie_id == cookie_id)]))
    

    It should work as expected:

    >>> print select([exists().where(users.c.name=='test')])
    SELECT EXISTS (SELECT *
    FROM users
    WHERE users.name = :name_1)
    

    Now, should you use exists or limit? Frankly I have no idea, and I'm not even sure the answer doesn't depend on your database engine...

    0 讨论(0)
提交回复
热议问题