SELECT中的多重连接

3 投票
2 回答
1029 浏览
提问于 2025-04-18 00:07

我有三个表,这些表通过ForeignKey约束连接在一起,这样sqlalchemy就知道怎么把它们连接起来。

我想从这三个表中选择一些列:

select([a.c.x, b.c.x, c.c.x], a.c.a.between(10,20), [join(a, c), join(a, b)])

这会生成一个有问题的SQL语句:

SELECT a.x, b.x, c.x
FROM
   a JOIN b ON a.b_id == b.id,
   a JOIN c ON a.c_id == c.id
WHERE
   a.a BETWEEN 10 AND 20;

可以看到,表aFROM语句中出现了两次!

我该如何在一个select()语句中使用sqlalchemy连接这三个表呢?

2 个回答

0

试试看下面的内容。

SELECT a.x, b.x, c.x
FROM *TABLENAME* a
JOIN *TABLENAME* b
ON a.id = b.id
JOIN *TABLENAME* c
ON a.id = c.id
WHERE
a.a BETWEEN 10 AND 20
1

简短的回答是

    select([a.c.x, b.c.x, c.c.x]).\
        select_from(a.join(b).join(c)).\
        where(between(a.c.a, 5, 15))

如果有人想试试,这里是完整的代码。

    import sqlalchemy
    from sqlalchemy import Table, Column, Integer, String, Sequence,\
        ForeignKey, select, between


    meta = sqlalchemy.MetaData()
    url = 'sqlite:///:memory:'
    engine = sqlalchemy.create_engine(url)


    a = Table(
        'a', meta,
        Column('id', Integer, Sequence('a_id_seq'), primary_key=True),
        Column('age', Integer),
        Column('name', String(20))
    )

    b = Table(
        'b', meta,
        Column('a_id', Integer, ForeignKey("a.id")),
        Column('value', String(20))
    )

    c = Table(
        'c', meta,
        Column('a_id', Integer, ForeignKey("a.id")),
        Column('title', String(20))
    )

    # Create tables
    meta.create_all(engine)

    # Fill with dummy data
    def add_data(age, name, value, title):
        q = a.insert().values({a.c.age: age, a.c.name: name})
        res = engine.execute(q)
        a_id = res.inserted_primary_key[0]

        q = b.insert().values({b.c.a_id: a_id, b.c.value: value})
        engine.execute(q)

        q = c.insert().values({c.c.a_id: a_id, c.c.title: title})
        engine.execute(q)

    add_data(12, 'Foo', 'Bar', 'Baz')
    add_data(17, '111', '222', '333')

    q = select([a.c.name, b.c.value, c.c.title]).\
        select_from(a.join(b).join(c)).\
        where(between(a.c.age, 5, 15))

    print(str(q))
    # SELECT a.name, b.value, c.title
    # FROM a JOIN b ON a.id = b.a_id JOIN c ON a.id = c.a_id
    # WHERE a.age BETWEEN :age_1 AND :age_2

    res = engine.execute(q)
    for row in res.fetchall():
        print(row)
        # ('Foo', 'Bar', 'Baz')

更新的回答,感谢评论者 Will

撰写回答