mysql SELECT IN 后跟逗号分隔字段
我使用 mySQL,并且有一个成员表,其中包含 BLOB“联系人”字段,其中包含其他成员 ID 的逗号分隔列表:
TABLE members:
id_member = 1
firstname = 'John'
contacts (BLOB) = '4,6,7,2,5'
我想通过单个查询检索个人“联系人”列表中的所有名字。我尝试了以下操作:
SELECT firstname from members WHERE id_member IN ( SELECT contacts FROM members WHERE id_member = 1 );
它仅返回一行,但是当我尝试时:
SELECT firstname from members WHERE id_member IN ( 4,6,7,2,5 );
它返回列表中的所有名字。我可以使用两个查询来实现这一目标,但我想我应该仔细检查是否有一种方法可以使其与一个简单、优雅的查询一起使用。
感谢您的阅读,任何帮助表示赞赏。 七月
I use mySQL and I have a members table with a BLOB 'contacts' field containing a comma separated list of other member's IDs:
TABLE members:
id_member = 1
firstname = 'John'
contacts (BLOB) = '4,6,7,2,5'
I want to retrieve all the first names in the 'contacts' list of an individual, with a single query. I tried the following:
SELECT firstname from members WHERE id_member IN ( SELECT contacts FROM members WHERE id_member = 1 );
It returns only one row, but when I try:
SELECT firstname from members WHERE id_member IN ( 4,6,7,2,5 );
It returns all the first names from the list. I can use two queries to achieve this, but I thought I'd double check if there's a way to make it work with one simple, elegant query.
Thanks for reading, any help appreciated.
Jul
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这看起来是一个非常糟糕的桌子设计。可以改变吗?
如果您无法更改设计,那么您可以使用
FIND_IN_SET
但它无法有效地使用索引:但我不会走这条路,强烈 建议如果可能的话标准化您的数据库。考虑使用连接表而不是逗号分隔的列表。然后您可以通过使用连接找到您需要的条目,并且搜索将能够使用索引。
That seems like a very poor table design. Is it possible to change it?
If you can't change the design then you can handle comma separated values in MySQL by using
FIND_IN_SET
but it won't be able to use indexes efficiently:But rather than going this route, I'd strongly recommend that if possible you normalize your database. Consider using a join table instead of a comma separated list. Then you can find the entries you need by using joins and the search will be able to use an index.
如果您使用序列化的 BLOB 类型列来存储这些值,那么您将无法执行您想要的操作。一种对 SQL 更友好的方法是创建一个可用作
JOIN
操作一部分的关系表,例如在一个之间具有关联的
值和其他一些。member_contacts
表。 id_member将逗号分隔列表扩展为单独的记录是一个非常简单的机械过程。
If you're using a serialized
BLOB
type column to store these values then you're not going to be able to do what you want. A more SQL friendly approach is to create a relationship table that can be used as part of aJOIN
operation, such as amember_contacts
table that has an association between oneid_member
value and some other.Expanding your comma separated list into individual records is a pretty simple mechanical process.
你能改变这个数据库结构吗?联系人字段实际上应该是一个相关的表而不是列。假设联系人表具有以下结构:
那么您将使用 EXISTS 代替:
Can you change this DB structure? The contacts field really should be a related table rather than a column. Assuming a contacts table with this structure:
Then you would use EXISTS instead: