如何强制SQLAlchemy包含重复列?

时间:2023-01-13 15:50:31

I'm learning the SQLAlchemy Expression Language, and I'm trying to execute a trivial query that returns a single duplicated column via select([users.c.id, users.c.id]):

我正在学习SQLAlchemy表达式语言,并尝试执行一个简单的查询,该查询通过select([users.c]返回一个重复的列。id,users.c.id]):

from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, insert, select
engine = create_engine('sqlite:///:memory:', echo=True)
conn = engine.connect()
metadata = MetaData()
users = Table('users', metadata,
Column('id', Integer, primary_key=True),
Column('name', String),
Column('fullname', String),
)
metadata.create_all(engine)
conn.execute(users.insert(), [
{'id': 1, 'name' : 'jack', 'fullname': 'Jack Jones'},
{'id': 2, 'name' : 'wendy', 'fullname': 'Wendy Williams'},
])
print(list(conn.execute(select([users.c.id, users.c.id]))))

Which outputs:

输出:

[(1,), (2,)]

I.e., only one of the two requested columns. I expected:

即。,在请求的两个列中只有一个列。我期望:

[(1, 2), (2, 2)]

To double-check that my expectations are correct, I ran the equivalent queries directly in sqlite3 and PostgreSQL 9.2 ([1] and [2] below), both of which correctly returned the duplicated ids. I'm using SQLAlchemy version 0.8.0b2, Python 3.2.3, sqlite3 3.6.12, and Mac OS X 10.6 and 10.7.

为了再次检查我的期望是否正确,我直接在sqlite3和PostgreSQL 9.2([1]和[2])中运行了等效查询,这两个查询都正确地返回了重复的id。我使用的是SQLAlchemy版本0.8.0b2、Python 3.2.3、sqlite3 3.6.12和Mac OS X 10.6和10.7。

Thanks in advance!

提前谢谢!

[1] sqlite3

[1]sqlite3

$ sqlite3 temp.db
CREATE TABLE users(id INTEGER, name TEXT, fullname TEXT);
INSERT INTO users VALUES(1, 'jack', 'Jack Jones');
INSERT INTO users VALUES(2, 'wendy', 'Wendy Williams');
SELECT id, id FROM users;
->
1|1
2|2

[2] PostgreSQL

[2]PostgreSQL

$ /Library/PostgreSQL/9.2/bin/psql -U postgres
CREATE DATABASE temp;
CREATE TABLE users(id INTEGER, name TEXT, fullname TEXT);
INSERT INTO users VALUES(1, 'jack', 'Jack Jones');
INSERT INTO users VALUES(2, 'wendy', 'Wendy Williams');
SELECT id, id FROM users;
->
1 |  1
2 |  2

1 个解决方案

#1


5  

At least one of your columns needs a label to create a distinction between the two.

至少有一个列需要一个标签来创建两者的区别。

print(list(conn.execute(select([users.c.id, users.c.id.label('id2')]))))

#1


5  

At least one of your columns needs a label to create a distinction between the two.

至少有一个列需要一个标签来创建两者的区别。

print(list(conn.execute(select([users.c.id, users.c.id.label('id2')]))))