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

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

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路