I’m trying to create a complex SQL query (at least for me) but really don’t know where to start.
Basically, I have a character object, and each character can be made of several parts. For example:
character table:
id | character
--------------
1 | 你
2 | 是
3 | 有
character_parts table:
id | character_id | part_id
---------------------------
1 | 1 | 4
2 | 1 | 9
3 | 1 | 5
4 | 2 | 2
5 | 2 | 34
6 | 2 | 43
7 | 3 | 21
8 | 3 | 16
9 | 3 | 41
10 | 3 | 43
So from that I know that:
Character 1 is made of parts 4, 9, 5
Character 2 is made of parts 2, 34, 43
Character 3 is made of parts 21, 16, 41, 43
Now what I would like to do is select all the characters that end by the specified parts.
For example, if I select all the characters that end by “16, 41, 43”, I’ll get Character 3. If I select all the characters that end by “43”, I’ll get Character 3 and 4.
I assume I need to build some query with subqueries, but not sure how to start, or if it can be done at all. So far I’m just selecting everything that include the required part IDs and then doing the comparison programmatically but this is too slow being I’m selecting way more than needed.
Any suggestion?
You could try
group_concatfunction:http://www.sqlite.org/lang_aggfunc.html
SELECT group_concat(part_id) FROM character_parts WHERE character_id=1The query should return
4,9,5.The problem is that the order used by
group_concatis arbitrary:Sqlite group_concat ordering
So, assuming you have a field
positionthat defines the order of the parts, we can update the query like this:SELECT group_concat(part_id) FROM (SELECT part_id FROM character_parts WHERE character_id=1 ORDER BY position ASC)The query will now return the
4,9,5parts exactly the defined order.Now that we have this value, we can search though it like a regular string.
If we want to find all values ending with a certain string, we could use
LIKEoperator.Finally the query would like like this: