Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write multi column in clause with sqlalchemy

Please suggest is there way to write query multi-column in clause using SQLAlchemy?

Here is example of the actual query:

SELECT  url FROM pages WHERE (url_crc, url) IN ((2752937066, 'http://members.aye.net/~gharris/blog/'), (3799762538, 'http://www.coxandforkum.com/'));

I have a table that has two columns primary key and I'm hoping to avoid adding one more key just to be used as an index.

PS I'm using mysql DB.

Update: This query will be used for batch processing - so I would need to put few hundreds pairs into the in clause. With IN clause approach I hope to know fixed limit of how many pairs I can stick into one query. Like Oracle has 1000 enum limit by default.

Using AND/OR combination might be limited by the length of the query in chars. Which would be variable and less predictable.

like image 451
vvladymyrov Avatar asked Dec 09 '13 02:12

vvladymyrov


People also ask

How do I join two columns in SQLAlchemy?

You can use . join() and then specify the join condition with the second param. If you omit the join condition, then the . query() method alone generates a cross join between table1 and table2.

What is subquery in SQLAlchemy?

The grouping is done with the group_by() query method, which takes the column to use for the grouping as an argument, same as the GROUP BY counterpart in SQL. The statement ends by calling subquery() , which tells SQLAlchemy that our intention for this query is to use it inside a bigger query instead of on its own.

What does all () do in SQLAlchemy?

all() method. The Query object, when asked to return full entities, will deduplicate entries based on primary key, meaning if the same primary key value would appear in the results more than once, only one object of that primary key would be present.


1 Answers

Assuming that you have your model defined in Page, here's an example using tuple_:

keys = [
    (2752937066, 'http://members.aye.net/~gharris/blog/'),
    (3799762538, 'http://www.coxandforkum.com/')
]

select([
    Page.url
]).select_from(
    Page
).where(
    tuple_(Page.url_crc, Page.url).in_(keys)
)

Or, using the query API:

session.query(Page.url).filter(tuple_(Page.url_crc, Page.url).in_(keys))
like image 167
ernematthew Avatar answered Sep 28 '22 07:09

ernematthew