Create an SQL query using the SqlAlchemy select and join functions

I have two tables: "tags" and "deal_tag", and the table is a table,

Table('tags', metadata,
          Column('id', types.Integer(), Sequence('tag_uid_seq'),
              primary_key=True),
          Column('name', types.String()),
         )

Table('deal_tag', metadata,
       Column('dealid', types.Integer(), ForeignKey('deals.id')),
       Column('tagid', types.Integer(), ForeignKey
           ('tags.id')),
        )

I want to select a tag identifier, tag name and number of deals (number of deals per tag). Request example

SELECT tags.Name,tags.id,COUNT(deal_tag.dealid) FROM tags INNER JOIN
deal_tag ON tags.id = deal_tag.tagid GROUP BY deal_tag.tagid;

How to create the above query using the SqlAlchemy select and join functions?

+3
source share
2 answers

Try to try ...

s = select([tags.c.Name, tags.c.id, func.count(deal_tag.dealid)], 
           tags.c.id == deal_tag.c.tagid).group_by(tags.c.Name, tags.c.id)
+2
source

you can join the table while displaying the table

in orm.mapper ()

for more information you can follow the link

www.sqlalchemy.org/docs/

0
source

Source: https://habr.com/ru/post/1709775/


All Articles