3

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?

2
  • If you have to use city_id how can you get it without using cities table. session.query(City) Here you are also querying the City table. Commented Aug 22, 2017 at 15:52
  • 1
    Yup, you were right, I just switched it to query(destination_city) and that fixed it. That makes sense. Thanks! Commented Aug 22, 2017 at 16:02

1 Answer 1

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.