Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy select_from a single table

In trying to replicate a MySQL query in SQL Alchemy, I've hit a snag in specifying which tables to select from.

The query that works is

SELECT c.*
FROM attacks AS a INNER JOIN hosts h ON a.host_id = h.id
  INNER JOIN cities c ON h.city_id = c.id
GROUP BY c.id;

I try to accomplish this in SQLAlchemy using the following function

def all_cities():
    session = connection.globe.get_session()
    destination_city = aliased(City, name='destination_city')
    query = session.query(City). \
        select_from(Attack).\
        join((Host, Attack.host_id == Host.id)).\
        join((destination_city, Host.city_id == destination_city.id)).\
        group_by(destination_city.id)

    print query

    results = [result.serialize() for result in query]

    session.close()
    file(os.path.join(os.path.dirname(__file__), "servers.geojson"), 'a').write(geojson.feature_collection(results))

When printing the query, I end up with ALMOST the right query

SELECT
  cities.id         AS cities_id,
  cities.country_id AS cities_country_id,
  cities.province   AS cities_province,
  cities.latitude   AS cities_latitude,
  cities.longitude  AS cities_longitude,
  cities.name       AS cities_name
FROM cities, attacks
  INNER JOIN hosts ON attacks.host_id = hosts.id
  INNER JOIN cities AS destination_city ON hosts.city_id = destination_city.id
GROUP BY destination_city.id

However, you will note that it is selecting from cities, attacks...

How can I get it to select only from the attacks table?

like image 692
Anders Hokinson Avatar asked Feb 12 '26 16:02

Anders Hokinson


1 Answers

The line here :

query = session.query(City)

is querying the City table also that's why you are getting the query as

FROM cities, attacks
like image 68
0decimal0 Avatar answered Feb 14 '26 05:02

0decimal0