开发者

Query for match in MySQL ListOfValues

Whats the best way to query MySql when I want the query return all rows where at least one value in a list of values matches at least one value in a list of values?

example

If my table contains the following rows:

name         groups
item1        gr1, gr2
item2        gr1,gr2,gr3
item3        gr1,gr3

And I have a list of values: "gr3,gr4,gr5"

I want to find all the rows in my table that have at least one of the values gr3,gr4 or gr5 in its groups field.

So the query in this case should return item2 and item3

How can I construct an efficient query without l开发者_如何学运维ooping in my script?


Personally I would suggest this isn't the best way to structure your database. I would have a link table, something like item_groups which would hold one row for each item-group link, so what you have there would be:

item_name         group_name
item1        gr1
item1        gr2
item2        gr1
item2        gr2
item2        gr3
item3        gr1
item3        gr3

This way you can simply do

SELECT item_name FROM item_groups WHERE group_name IN ('gr3','gr4','gr5');

This is what I was taught when I covered Database theory as part of my BSc, and whilst it does result in more tables, it makes searching a lot quicker and easier. HTH

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜