简体   繁体   English

MySql SELECT * FROM table_name WHERE col_name IN(任何值)

[英]MySql SELECT * FROM table_name WHERE col_name IN (any value)

I am dynamically generating a python tuple我正在动态生成一个 python 元组

x = (1, 3)

So I can use MySql query in python like below,所以我可以在 python 中使用 MySql 查询,如下所示,

f"SELECT * FROM table_name WHERE col_name IN {x}"

and it worked without problem.它没有问题。

But when I use empty tuple as x ( x = () ), I want the query to return all values of the table (just ignore the condition)但是当我使用空元组作为 x ( x = () )时,我希望查询返回表的所有值(只需忽略条件)

I know that I can use a if in python and pass the filter to sql only if x is not null.我知道我可以在 python 中使用 if 并仅在 x 不是 null 时将过滤器传递给 sql。 But I want to use this in sql so it will be easier because the actual query string is so long and has the same problem in many places.但是我想在 sql 中使用它,这样会更容易,因为实际的查询字符串很长并且在很多地方都有同样的问题。

So my question is,所以我的问题是,

IS THERE A WAY IN MYSQL LIKE BELOW, MYSQL 中是否有如下方法,

SELECT * FROM table_name WHERE col_name IN (%)

just like we use就像我们使用

SELECT * FROM table_name WHERE col_name LIKE "%"

Came up with this python way.想出了这种 python 方式。 define a function like so:像这样定义一个 function :

def queryfriendly(value):
    if isinstance(value, str):
        return f'"{value}"'
    return str(value)

def tuple_to_condition(col_name, tup):
    if len(tup):
        return f'{col_name} IN (' + ', '.join(list(map(queryfriendly, tup))) + ')'
    return 'TRUE'

Now in your query strings do this:现在在您的查询字符串中执行以下操作:

f"SELECT * FROM table_name WHERE {tuple_to_condition('col_name', x)}"

The function just returns 'TRUE' so that the WHERE won't throw an error. function 只返回“TRUE”,这样WHERE就不会抛出错误。

def sql_escape(s, replace_all=False):
if replace_all:
    s = s.replace("_", "\\_").replace("%", "\\%")
return s.replace("\\", "\\\\") \
    .replace("\'", "\\\'") \
    .replace("\"", "\\\"")
def sql_in(col, values, default="TRUE"):
    if values is None:
        return default
    values = set(values) - {""}
    if len(values):
        values = ",".join("\'" + sql_escape(str(v).strip()).replace("%", "\\%").replace("_", "\\_") + "\'"
                          for v in values)
        return f"{col} IN ({values})"
    else:
        return default

After trying out some codes, I found this as the answer.在尝试了一些代码后,我发现这是答案。

x = [value1, value 2] # a list,, not a tuple
x.append("some value that does not in table")
x = tuple(x)

So the tuple won't be null.所以元组不会是 null。 Now we can get a help from eshirvana's answer现在我们可以从 eshirvana 的回答中得到帮助

SELECT * FROM table_name WHERE col_name IN {x} OR {len(x) > 1}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python 或 Pandas 数据汇总(将表格转换为 row_name 的字典:[col_name, value]…) - Python or Pandas Data Summarization(Converting Table into Dictionary of row_name:[col_name, value]…) select_from(table_name)中的table_name是什么类型? - What is the type of table_name in select_from(table_name)? 如何避免使用“SELECT * FROM {table_name}”进行 SQL 注入? - How to avoid SQL injection with “SELECT * FROM {table_name}”? 如何使用来自 df.itertuples() 的 Namedtuple Pandas 启用 row[col_name] 语法 - How to enable row[col_name] syntax with Namedtuple Pandas from df.itertuples() 我可以像这样将python的`for`语句与SQL结合:`db.select('table_name',where ='...')中的for id,name,ctime。 - Can I combine python's `for` statement with SQL like this: `for id, name, ctime in db.select('table_name', where='…')` 有没有一种方法可以在redshift中使用CONCAT(table_name(col1,col2,col3,…))连接可变数量的列? - Is there a way to concatenate variable number of columns using CONCAT(table_name(col1, col2, col3,…)) in redshift? SELECT * FROM table_name仅给我一列作为结果 - SELECT * FROM table_name give me only one column as result 从名称=列表的表中选择数据? - select data from table where name = list? Pandas的[等效的SQL [df.groupby(...)['col_name']。shift(1)] - SQL equivalent for Pandas's [df.groupby(…)['col_name'].shift(1)] python: drop_duplicates(subset='col_name', inplace=True),为什么有些行不能删除? - python: drop_duplicates(subset='col_name', inplace=True), why some of the rows can not be dropped?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM