简体   繁体   English

mySql - 使用逗号分隔值列表创建连接

[英]mySql - creating a join using a list of comma separated values

I've got a table with a field for Merchant's name and field with the Services they provide. 我有一张桌子,上面有商家名字和字段,里面有他们提供的服务。 The Services field is a comma separated list of integers that relate to another Services table, with the Service id and the Service Name fields. “服务”字段是以逗号分隔的整数列表,它与另一个“服务”表相关,并带有“服务ID”和“服务名称”字段。

I'm trying to create a single query that joins those two, so I can have a list of Merchants, along with the Services Names. 我正在尝试创建一个连接这两个的单个查询,因此我可以列出商家列表以及服务名称。 My solution so far has been to do a second loop within my initial 'foreach' loop, but that can mean 5 or 6 db calls for each Merchant name. 到目前为止,我的解决方案是在我的初始'foreach'循环中进行第二次循环,但这可能意味着每个商家名称有5或6个db调用。

After some StackOverflow-ing (google-ing), I noticed that using a comma separated field is probably not the best way to go. 在一些StackOverflowing(google-ing)之后,我注意到使用逗号分隔字段可能不是最好的方法。

Anyone have either a way to do the join, or thoughts on how the db structure could be set up better? 任何人都有办法进行连接,或者想如何更好地设置数据库结构? Many thanks in advance! 提前谢谢了!

The short term solution to your issue is to use the FIND_IN_SET function to join the MERCHANT and SERVICES tables: 您的问题的短期解决方案是使用FIND_IN_SET函数来加入MERCHANT和SERVICES表:

SELECT *
  FROM MERCHANT m
  JOIN SERVICES s ON FIND_IN_SET(s.service_id, m.services) > 0

The long term solution is to correct your tables - never allow columns to contain comma separated lists of referential ID/etc values. 长期解决方案是更正表 - 永远不要允许列包含逗号分隔的引用ID / etc值列表。

Merchant
MerchantId   Name
          1   Adams Consulting

Merchant_Services
MerchantId    Service
         1    SEO
         1    Brand Consulting

You can actually get a comma separated list back: 您实际上可以获得以逗号分隔的列表:

SELECT m.*, GROUP_CONCAT(ms.Service) AS Services
FROM Merchant m
LEFT JOIN Merchant_Serivces ms
ON ms.MerchantId = m.MerchantId
GROUP BY m.MerchantId
ORDER BY m.Name, ms.Service

Results in: 结果是:

MerchantID  Name              Services
----------  ----------------  --------------------
         1  Adams Consulting  Brand Consulting,SEO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM