简体   繁体   中英

FIND_IN_SET in mysql query for double condition

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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