Scenario:
I have a main table, say " items
". Each item can be of many types, and I use a table " types
" and a linked table to keep the relations between the two, say " items_types
" in a typical one to many situation. Now, each type has a supertype, with a straight one to one relation.
items: i_id, i_name
types: t_id, t_name, t_st_id
items_types: it_id, it_i_id, it_t_id
supertypes: st_id, st_name
Now I have to filter all the items that are related to at least one supertype in a given set, say supertypes with ids 1,2,3
I am thinking to use a group_concat
on the ids of the related supertypes and then filtering using multiple FIND_IN_SET
in or between each other, using a WHERE
clause.
However this, if working, would slow down the query and I don't like comparing ids as if they were strings.
Any idea?
You can do like this.
select i.*
from items_types it
join items i on i.i_id = it.it_i_id
join types t on t.t_id = it.it_t_id
join supertypes st on st.st_id = t.t_st_id and st_id in (1,2,3)
I found a better solution: instead using related records to keep track of all the types the item belongs to, I am giving each type a numeric code which can be used in binary comparison, eg:
Type 1: code 1 Type 2: code 2 Type 3: code 4 Type 4: code 8 Type 5: code 10
I think I gave the idea.
Each item will have a field to keep track of all its types, named 'coded_type'. For example if a field has coded_type 7 it means that it belongs to Type 1, Type 2, Type 3.
For instance, if a user then wants to look for all items that are of type 2 or 3 the query will look for all items whose coded_type field binary ANDed against 6 gives a value greater than zero.
That is:
select * from items where (coded_type & 6)>0
I think this way the query will much simpler and run faster. Sorry I thought of this just now.
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.