views:

1290

answers:

2

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?

+1  A: 

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)
EPiddy
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.
Ants Aasma
A: 

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/

nazmul hasan