3

I have two tables "tags" and "deal_tag", and table definition follows,

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 tag id, tag name and deal count (number of deals per tag). Sample query is

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 do I create the above query using SqlAlchemy select & join functions?

2 Answers 2

2

Give this a 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)
Sign up to request clarification or add additional context in comments.

1 Comment

You forgot the .group_by(deal_tag.c.tagid). And this will not work on DBs that respect the SQL standard, you need to group by tags.c.Name and tags.c.id, because they are selected.
0

you can join table in the time of mapping table

in the orm.mapper()

for more information you can go thru the link

www.sqlalchemy.org/docs/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.