简体   繁体   English

在 Sql Alchemy 中,如何在 select 行中的任何列包含 substring?

[英]In Sql Alchemy, how to select rows where any column contains a substring?

I want to retrieve all the rows of a table where a substring "h" is contained in any of the columns)我想检索任何列中包含 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ“h”的表的所有行)

I tried something like this:我试过这样的事情:

list_of_columns = [c for c in my_table.columns] # where my_table is of class Table

with my_engine.connect() as conn:

    result = conn.execute(select(my_table).where(
            list_of_columns.contains(q),
    ))

Of course this does not work, as " contains() " should be called on a single column...当然这不起作用,因为应该在单个列上调用“ contains() ”......

Any idea?任何想法?

ps: the retrieving of the columns must be dynamic, this is the way my code must work ps:列的检索必须是动态的,这是我的代码必须工作的方式

[EDIT] [编辑]

An almost working solution:一个几乎可行的解决方案:

with my_engine.connect() as conn:

    result = conn.execute(select(my_table).where(
            or_(
                list_of_columns[0].contains(q),
                list_of_columns[1].contains(q),
                ...
            )
    ))

But, I need the listing of the columns to be dynamic但是,我需要列的列表是动态

You can use a list comprehension to add all the columns to the query:您可以使用列表推导将所有列添加到查询中:

with my_engine.connect() as conn:
    result = conn.execute(select(my_table).where(
        or_(*[col.contains(q) for col in list_of_columns])
    ))

For this kind of search, you might also get better performance and results by using postgresql's full-text search functionality, and creating a tsvector that combines all of the columns: https://stackoverflow.com/a/42390204/16811479对于这种搜索,您还可以通过使用 postgresql 的全文搜索功能并创建一个组合所有列的 tsvector 来获得更好的性能和结果: https://stackoverflow.com/a/42390204/16811479

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

相关问题 Pandas:删除任何列包含某个子字符串的所有行 - Pandas: Remove all rows where any of the column contains a certain substring Pandas 数据框选择列表列包含任何字符串列表的行 - Pandas dataframe select rows where a list-column contains any of a list of strings 最简洁的方法是 select 行,其中任何列包含 Pandas dataframe 中的字符串? - Most concise way to select rows where any column contains a string in Pandas dataframe? 如果任何列包含某个 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ,如何保持一行? - How to keep a row if any column contains a certain substring? 获取其中任何列包含特定值的行的子集 - Get subset of rows where any column contains a particular value 如何从熊猫数据框中删除行,其中任何列都包含我不想要的符号 - How to drop rows from a pandas dataframe where any column contains a symbol I don't want 从 Pandas 数据框中选择特定列包含数字的行 - Select rows from Pandas dataframe where a specific column contains numbers 熊猫-在ANY列中选择包含某个正则表达式的数据框的行 - Pandas - Select rows of a dataframe that contains a certain regex in ANY column 总和 DataFrame 行一列包含 substring - Sum DataFrame rows a column contains a substring SQLAlchemy 查询,其中列包含 substring - SQLAlchemy query where a column contains a substring
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM