SQLAlchemy SELECT混乱

时间:2011-05-29 05:31:57

标签: sql select sqlalchemy

我正在浏览this SQLAlchemy tutorial,并且对以下示例感到非常困惑(大约在页面的中间位置):

>>> 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',)]

(users.c.fullname + ", " + addresses.c.email_address)如何识别要选择的列?这是否意味着它会查找标题为"fullname, email_address"的列?我明显误解了一些事情。结果[(u'Wendy Williams, wendy@aol.com',)]与给予SELECT的字符串的格式相同。我只是不明白它是如何工作的。

以前从未做过数据库;我在学习SQL的同时学习SQLAlchemy,所以我的问题完全可能是SQL而不是SQLAlchemy。

1 个答案:

答案 0 :(得分:0)

users.c.fullname是一个聪明的对象,会重载+运算符。 users.c.fullname + ", "创建表示表达式的ClauseElement,SQLAlchemy知道如何转换为任何SQL引擎的语法。同样的原因你可以做users.c.name.between('m', 'z'); users.c.name是一个对象,其between方法返回ClauseElement