在带有 python 列表的 sql 查询中使用 isin [英] Using isin in a sql query with a python list
问题描述
我一直在为不同类型的项目使用以下类型的查询 + Pandas 代码,并且我正在尝试找到尽可能直接在 SQL 中执行的方法:
I have been using the following type of query + pandas code for different types of projects, and I am trying to find ways to do as much as possible directly in SQL instead:
import mysql.connector
list = [10,15]
sql = "select value, employee_id from employee_table"
df = pd.read_sql(sql,conn)
df_new = df.employee_id.isin(list)
所以上面的代码将只选择employee_id为10和15的薪水.在SQL中,它看起来像这样:
So the above code would select only the salary for the employee_id of 10 and 15. In SQL, it would look like this:
select value, employee_id
from employee_table
where employee_id in (10,15)
我的问题是如何使用 python 列表在 python 中执行上述查询?如果它很重要,我正在使用 Mysql.
My question is how can I do the above query in python with a python list? I am using Mysql if it is of importance.
推荐答案
如果您希望输出是与示例 SQL 查询具有相似输出的 Pandas DataFrame,您可以简单地执行以下操作:
If you want your output to be a pandas DataFrame that would have a similar output to your example SQL query, you can simply do:
df[df.employ_id.isin(list)]
这篇关于在带有 python 列表的 sql 查询中使用 isin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!