SQLAlchemy SELECT confusion
I'm going through this SQLAlchemy tutorial and have become very confused by the following example (about halfway down the page):
>>> s = select([(users.c.fullname + ", " + addresses.c.email_address).label('title')],
... and_(
... users.c.id==addresses.c.user_id,
... users.c.name.between('m', 'z'),
... or_(
... addresses.c.email_address.like('%@aol.com'),
... addresses.c.email_address.like('%@msn.com')
... )
... )
... )
>>> print conn.execute(s).fetchall()
SELECT users.fullname || ? || addresses.email_address AS title
FROM users, addresses
WHERE users.id = addresses.user_id AND users.name BETWEEN ? AND ? AND
(addresses.email_address LIKE ? OR addresses.email_address LIKE ?)
(', ', 'm', 'z', '%@aol.com', '%@msn.com')
[(u'Wendy Williams, wendy@aol.com',)]
How does (users.c.fullname + ", " + addresses.c.email_address)
identify columns to select from-- doesn't that mean it looks for columns titled "fullname, email_address"
? I'm clearly misunderstanding something. The result [(u'Wendy William开发者_如何学Pythons, wendy@aol.com',)]
is the same format as the string given to SELECT.. I just don't understand how that works.
Never done databases before; I'm learning SQLAlchemy at the same time I'm learning SQL, so it's entirely possible my problem is with SQL not SQLAlchemy.
users.c.fullname
is a clever object that overloads the +
operator. users.c.fullname + ", "
creates a ClauseElement
representing the expression, which SQLAlchemy knows how to translate to any SQL engine's syntax. Same reason you can do users.c.name.between('m', 'z')
; users.c.name
is an object with a between
method that returns a ClauseElement
.
精彩评论