且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 MySQL 中选择包含多个值的行?

更新时间:2023-01-31 15:30:49

你真的不应该那样存储你的数据,因为它会使查询效率极低.对于该特定用例,您可以(如果您不关心性能)使用:

You really shouldn't store your data like that since it makes queries horribly inefficient. For that particular use case, you can (if you don't care about performance) use:

select * from designer
    where gallery like '36,%'
       or gallery like '%,36'
       or gallery like '%,36,%'
       or gallery = '36'

这将减轻您对部分匹配的担忧,因为诸如 136 之类的内容不会匹配任何这些条件,但任何位置的 36 都会匹配.

This will alleviate your concerns about partial matches since something like 136 will not match any of those conditions but 36 in any position will match.

然而,尽管您提出了相反的***,但您应该做的是重新设计您的架构,例如:

However, despite your protestations to the contrary, what you should do is re-engineer your schema, something like:

designer:
    id             integer primary key
    name           varchar(whatever)
designer_galeries:
    designer_id    integer foreign key references designer(id)
    gallery        string
    primary key    (designer_id,gallery)

那么您的查询速度会非常快.您应该学习的第一件事之一是始终为第三范式设计架构.一旦您了解了权衡取舍(并知道如何减轻问题),您就可以恢复到其他形式的性能,但除非您的数据库非常复杂,否则很少有必要这样做.

Then your queries will be blindingly fast. One of the first things you should loearn is to always design your schema for third normal form. You can revert to other forms for performance once you understand the trade-offs (and know how to mitigate problems) but it's rarely necessary unless you database is horribly convoluted.