我在VB.NET中写了一个“电影”程序
用户可以创建自定义过滤器,他们可以根据类型,导演,发行年份等一些简单的内容指定他们想要在列表中看到哪些电影。
表电影:
ID Title Director Year Genres Description Image
由于电影(或电视节目)可以有更多类型,我最终将这些类型存储到1个字符串中;作为分隔符。
示例:
a01;a02;b08;c01
当然,我的应用程序会在检索结果时将a01转换为适当的“恐怖”或“惊悚”类型等。
我的问题是:是否可以创建一个自己进行过滤的SQLite查询?目前我正在创建如下的查询:
SELECT *
FROM `movies`
WHERE (`Year` = 2013)
AND (`Genres` LIKE '%a02%' OR `Genres` LIKE '%g05%')
这样可以解决问题,但是根据一些自定义过滤器,您最终可能会遇到超过10kb字符的查询。
SQLite中是否存在某种SPLIT函数,以便我可以这样查询:
SELECT *
FROM `movies`
WHERE (`Year` = '2013')
AND (SPLIT(`Genres`,';') IN ('a01','v05','c01'))
非常感谢任何帮助
答案 0 :(得分:0)
[对不起T-SQL,但MS SQL Server是我必须要证明的。如果SQLite不一样,SQL应该非常相似。]
你应该做的是为流派创建另一个表:
然后用
之类的东西查询它SELECT DISTINCT M.[ID] AS [ID], [Title] AS [Title] FROM Movies AS M
JOIN [MovieGenre] AS MG
ON M.ID = MG.ID
WHERE (MG.Genre IN ('A01', 'A02'))
AND M.[Year] = 2010
从我能够快速了解一下,在SQLite How to split comma-separated value in SQLite?中将字符串拆分成表格有点繁琐 - 请注意评论。
但是,如果可以,那么您可以使用类似
的内容-- This is a temporary table in SQL Server.
-- It is only to illustrate joining onto a table of
-- user-selected genres
CREATE TABLE #genres
(
Genre NCHAR(10)
)
INSERT INTO #genres VALUES ('A01');
INSERT INTO #genres VALUES ('B01');
-- The query:
SELECT DISTINCT M.[ID] AS [ID], [Title] AS [Title] FROM Movies AS M
JOIN [MovieGenre] AS MG
ON M.ID = MG.ID
JOIN #genres AS TempG
ON TempG.Genre = MG.Genre
AND M.[Year] = 2010
其中#genres
表是分割字符串的表。
然而当您在VB.NET中创建查询时,您可以轻松地在其中拆分字符串并使用它来轻松地构建一个IN
子句 - 一个小的代码示例说明:
Module Module1
Sub Main()
Dim userSelectedGenres = "A01;A02"
Dim gs = userSelectedGenres.Split(";"c)
Dim inClause = String.Join(",", gs.Select(Function(g) "'" & g & "'"))
Dim sqlString = <sql>SELECT DISTINCT M.[ID] AS [ID], [Title] AS [Title] FROM Movies AS M
JOIN [MovieGenre] AS MG
ON M.ID = MG.ID
WHERE (MG.Genre IN (<%= inClause %>))
AND M.[Year] = 2010
</sql>.Value
Console.WriteLine(sqlString)
Console.ReadLine()
End Sub
End Module
输出:
SELECT DISTINCT M.[ID] AS [ID], [Title] AS [Title] FROM Movies AS M
JOIN [MovieGenre] AS MG
ON M.ID = MG.ID
WHERE (MG.Genre IN ('A01','A02'))
AND M.[Year] = 2010