SQLite 部分整数匹配

SQLite matching on partial integer

我有以下代码:

sic_code = int(input("Filter by SIC code (1-4 digits)? Default is all: ")

# Connect to the database file
conn = sqlite3.connect(db)
c = conn.cursor()

sql = ("SELECT Name "
       "FROM stock_data "
       "WHERE SIC_Code = {sc}".format(sc=sic_code))

# Run SQL query
c.execute(sql)

这是 SIC 代码在数据库中的样子。

理想情况下,无论用户输入的是 7、73、737 还是 7372,我都希望匹配 7372。我尝试从匹配 4 位代码的简单查询开始,但我无法让它工作.查询 returns 没有行。没有 SIC 查询,一切正常。

SIC 列和用户输入变量都指定为整数。

在此先感谢您的帮助。

您正在 sqlite 中查找 LIKE

您将 %_LIKE 运算符一起使用

当你想匹配字符串的某些部分时使用%,例如

h% 将匹配 hot , hell...

h_t 将匹配 hut,hit..

LIKE 适用于 VARCHAR 而不是 integer 所以 w.rt 如果你想使用 LIKE 匹配 integer 你的问题您必须将它们存储为 VARCHAR 的值,然后使用

#input sic_code should be string
sic_code = input("Filter by SIC code (1-4 digits)? Default is all: ")
sic_code = sic_code + '%' #where SIC_code is stored as `VARCHAR`
SELECT Name FROM stock_data WHERE SIC_Code LIKE {sc}".format(sc=sic_code)

您可以使用CAST

#input sic_code should be string
sic_code = input("Filter by SIC code (1-4 digits)? Default is all: ")
sic_code = sic_code + '%' #where SIC_code is stored as `integer`
SELECT Name FROM stock_data WHERE CAST(SIC_Code as TEXT) LIKE 
                                   {sc}".format(sc=sic_code)

*我没有使用过 cast 但阅读了文档。

None 以上解决方案对我有用。相反,我将 SQL 数据导出回 pandas 数据框并在那里应用正则表达式。

感谢您的帮助。

此致, 瑞安

使用regexp_match() from SQLAlchemy 1.4:

它也适用于整数类型的列。