简体   繁体   中英

search operation for CSV field sqlite

I have a SQLite table named User . Each User has a primary UserID and multiple SecIDs (all integers). The SecIDs are stored in CSV format as a single field (type is String). For example, suppose User1 has SecIDs as 4,5,6,7 and User2 has SecIDs as 8,9,55,66.

So for User1 :-
UserID = 1
SecIDs = "4,5,6,7"
And for User2 :-
UserID = 2
SecIDs = "8,9,55,66" (And so on)

Now my question is- I have a particular SecID say 5. And I have to extract the UserID corresponding to that (which is 1). So what would be the Query for this operation?

PS- There could be hundreds of thousands of User Records in my SQLite table. So the search query should be an optimized for minimum time consumption.

That's simply not how you do SQL or relational databases, so SQLite doesn't have a specific SELECT syntax for that. You can of course search all the field by a String patter ~"12" , for example, but that is a terrible idea, because it matches 12 as much as 128 as much as 112.

What you should do is re-structure your database. Get a 1-to-n mapping table to map SecIDs to users; it's not hard at all, a lot faster, and but a two-column table:

+-----+----+
|SecID|User|
+-----+----+
|    4|   1|
|    5|   1|
|    6|   1|
|    7|   1|
|    8|   2|
|    9|   2|
|   55|   2|
|   66|   2|
+-----+----+

It will be much faster, less error-prone, and much more compact in both RAM and permanent storage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM