dongyi0210 2013-10-14 06:13
浏览 167
已采纳

在单个查询中搜索逗号分隔的MySQL列中的多个值

I am fully aware of how bad it is to have Delimited Lists in a Table Column, instead of normalizing data into multiple tables.

Although, I do have a table structure designed years ago, which I will re-design soon.
Simplified, it looks like this:

Table: Newsletters
+------------+---------------+
| subject    | mailing_lists |
+------------+---------------+
| A Test     | 1,2           |
| More Tests | 2,3           |
+------------+---------------+ 

You can see it in this SQLFiddle, if you prefer to.

Recently, I gave my users the option to write a delimited list of mailing list ids (like 1,3), as a feature to select which newsletters to show in a view.
(e.g. Only show newsletters that were sent to lists with id 1 or 3)

So: A table column with a delimited list of ids, and delimited ids as an input.

This would obviously be much easier if the tables were normalized.

So, I solved this in PHP, by exploding the input ids and iterating them to create a query like the one in the fiddle mentioned above, which looks like this:

SELECT * FROM `newsletters`
  WHERE FIND_IN_SET("1", `mailing_lists`) > 0
     OR FIND_IN_SET("3", `mailing_lists`) > 0

This query perfectly fetches the data I want to get, but I can only create it programmatically, since I have to add a new condition for each id in my delimited list.

Question is: Out of pure curiosity: Is there a way to avoid the loop in PHP, and make a query without splitting the ids in code?

  • 写回答

2条回答 默认 最新

  • douhuan1950 2013-10-14 07:27
    关注

    After the very useful post by rakeshjain, I managed to transform my query into this:

    SELECT * FROM (SELECT *,
                   `mailing_lists` REGEXP REPLACE("1,3", ',', '(\\,|$)|')
                      as haslists
                   FROM `newsletters` B) A
      WHERE A.haslists = 1
    

    In the above, I assume that "1,3" is the value provided by the user.
    Here is the solved fiddle: http://sqlfiddle.com/#!2/4621b0/19

    Thank you rakeshjain!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题