dtg25862 2013-02-02 20:01
浏览 473
已采纳

mysql查询中的FIND_IN_SET为双重条件

i have a table like this

products : id , name , groups , domains

Here groups and domains are both comma seperated fields. I am working on an existing project and i can not change the structure. Here is the detail.

groups : id , name
domains : id , name

products

id      |   name    |   groups  |   domains
------------------------------------------------
1       |   A       |   1,2,3   |   0
2       |   B       |   1,2,3   |   0   
3       |   C       |   1,2,3   |   1,2 
4       |   D       |   2,3     |   1,3 
5       |   E       |   2,3     |   2,3 
6       |   F       |   2,3     |   2,3,4   
7       |   G       |   1,2,3   |   0   
8       |   H       |   1,2,3   |   0   
9       |   I       |   2,3     |   1,2,4   
10      |   J       |   3       |   1,3 
11      |   K       |   3       |   2,4 
12      |   L       |   3       |   2,3 
13      |   M       |   1,2,3   |   0   
14      |   N       |   1,2,3   |   0   
15      |   0       |   3       |   1,2,4   

domains

id  |   name
---------------------
1   |   yahoo   
2   |   gmail
3   |   mailinator
4   |   hotmail

groups

id  |   name
---------------------
1   |   General 
2   |   Contractor
3   |   Partner

Now i need to select all those which have these conditions.
How can i select products where

groups : 3
domains : 1

Note 0 means all(1,2,3,4)

  • 写回答

1条回答 默认 最新

  • doumei4964 2013-02-02 20:04
    关注

    It's a shame you cannot modify this, and +1 for wishing you were able to. But you have the right idea using FIND_IN_SET() . The only other thing to consider is an OR condition to account for the 0 (all) value. Give each condition the option of satisfying FIND_IN_SET() or being equal to 0.

    SELECT *
    FROM products
    WHERE (FIND_IN_SET(3, groups)
        OR groups = 0)
        AND (FIND_IN_SET(1, domains)
          OR domains = 0)    
    

    SQL Fiddle Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?
  • ¥15 QTOF MSE数据分析
  • ¥15 平板录音机录音问题解决