Php 和 MySQL GROUP_CONCAT 带分隔符逗号并搜索用逗号连接的位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16958908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:58:23  来源:igfitidea点击:

Php and MySQL GROUP_CONCAT with separator comma and search where concat by comma

phpmysqlconcatgroup-concat

提问by Jows

Is it that possible to select in Group_concat with separator comma and search where concat by comma Here My sample of mysql :

是否可以在 Group_concat 中使用分隔符逗号进行选择,并在此处用逗号搜索 concat 在哪里我的 mysql 示例:

products_attributes_id  |products_id|   options_id|     options_values_id 
39                  |   31      |       3     |         3   
35                  |   30      |       2     |         2   
38                  |   30      |       1     |         1   
40                  |   31      |       2     |         2   
41                  |   30      |       1     |         4   
42                  |   30      |       1     |         5   
43                  |   31      |       1     |         4 

I want to GROUP_CONCAT options_values_id

我想 GROUP_CONCAT options_values_id

SELECT * , GROUP_CONCAT(options_values_id SEPARATOR ',') FROM products_attributesGROUP by products_id

SELECT * , GROUP_CONCAT(options_values_id SEPARATOR ',') FROM products_attributesGROUP by products_id

products_attributes_id  |   products_id |   options_id  |   options_values_id   |   options_values_id
35                  |   30          |   2           |   2                   |   2,1,4,5
39                  |   31          |   3           |   3                   |   3,2,4

Now my problem is How I will find the product_id by searching ( option_values_id with comma) if my value is 1,2 or 2,4 then I will get only product_id=30. But if I got value 1,3 I will get nothing. Because product_id 30 don't have option_values_id 3 and product_id 31 don't have option_values_id 1.

现在我的问题是如果我的值为 1,2 或 2,4,我将如何通过搜索(带逗号的 option_values_id)找到 product_id,那么我将只得到 product_id=30。但是如果我得到值 1,3,我将一无所获。因为 product_id 30 没有 option_values_id 3 而 product_id 31 没有 option_values_id 1。

I try this code but I can't get the product_id

我尝试使用此代码,但无法获取 product_id

    SELECT * , GROUP_CONCAT( options_values_id
SEPARATOR ',' )
FROM `products_attributes` WHERE CONCAT(',',options_values_id,',') LIKE '%,1,2,%'
GROUP BY products_id

回答by Stephan

Try this:

尝试这个:

SELECT 
    products_id , 
    GROUP_CONCAT(options_values_id SEPARATOR ',') as ops 
FROM 
    products_attributes 
GROUP by 
    products_id
HAVING
    FIND_IN_SET('1',ops)
    OR FIND_IN_SET('3',ops)