【问题标题】:how to select elements by choose parameters from another table in SQLite3 python如何通过从 SQLite3 python 中的另一个表中选择参数来选择元素
【发布时间】:2018-04-02 17:18:19
【问题描述】:

是否可以从波兰 (country_id = 76) 返回城市列表(例如),但在 WHERE 中使用国家名称(country.country 行的值)而不是直接 country_id?数据库结构如下。

@app.route('/citiess')
def city_list3():
    db = get_db()
    data = db.execute('''
        SELECT city FROM city 
        JOIN country ON city.country_id = country.country_id
        WHERE city.country_id = 76
        ''').fetchall()
    data_json = []
    for i in data:
        data_json.extend(list(i))

    return jsonify(data_json)

【问题讨论】:

    标签: python python-3.x sqlite flask


    【解决方案1】:

    您为什么不在连接的country 表上执行WHERE 子句,即:

    data = db.execute("""SELECT city FROM city
                         JOIN country USING (country_id)
                         WHERE country.country = ?""", ("Poland", )).fetchall()
    

    【讨论】:

      【解决方案2】:

      我认为这也有效:

      data = db.execute('''
          SELECT city FROM city 
          JOIN country ON country.country_id = city.country_id
          WHERE country.country = "Poland"
          ''').fetchall()
      

      还是谢谢

      【讨论】:

      • 我只是对其进行了参数化,这样您就可以安全地为您想要的任何国家/地区重复使用您的查询,而不是直接更改 SQL。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-22
      • 1970-01-01
      • 1970-01-01
      • 2012-04-29
      • 2018-01-18
      • 1970-01-01
      相关资源
      最近更新 更多