在mysql中比较两个逗号分隔的值并获取匹配的计数 [英] compare two comma separated values in mysql and get the matched count

查看:114
本文介绍了在mysql中比较两个逗号分隔的值并获取匹配的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比较mysql中逗号分隔的值,并在countcolumn中获取匹配的输出

Compare comma separated values in mysql and get the matched output in countcolumn

示例:

id   values 
 1    1,2,3
 2    3
 3    1,3

通过比较ID 1和2,输出应为1

By comparing id 1 and 2 the output should be 1

通过比较ID 2和3,输出应为1

By comparing id 2 and 3 the output should be 1

通过比较ID 3和1,输出应为2

By comparing id 3 and 1 the output should be 2

推荐答案

首先,您列出的数据实际上应该以一种格式存储,数据库的每一行都存储一个id和一个value,即3元素列表将对应3行.如果对您的结构进行了更改,则以下答案将是相关的比较两个结果之间的相似性设置

Firstly, the data you listed should really be stored in a format where each row of the database stores a single id and a single value, i.e. the 3-element list would correspond to 3 rows. If that change was made to your structure then the following answer would be relevant Compare similarities between two result sets

尽管如此,这是我整理的一个不错的MySQL小功能,您可以将其用于您的目的.这将接受2个参数,这些参数是逗号分隔的列表,并将返回出现在列表2中的列表1中的元素数.

As it stands though, here's a nice little MySQL function I put together that you could use for your purposes. This takes in 2 arguments which are comma-separated lists and will return the number of elements in list 1 that appear in list 2.

这并不能阻止列表1中的重复ID在列表2中被计算两次(即"1,1,2"和"1,2"将返回值3),但是您可以弄清楚如何如果您愿意的话,可以很容易地对其进行调整.

This will not as it stands prevent duplicate IDs in list 1 being counted twice in list 2 (i.e. '1,1,2' and '1,2' would return a value of 3) but you could figure out how to adjust this fairly easily to do that if you so wished.

要使用此功能,只需执行

To use this, just do

SELECT 
    countMatchingElements( '3' , '1,3' ) AS testCase1
    countMatchingElements( '1,2,3' , '1,3' ) AS testCase2
    countMatchingElements( '3' , '1,2,3' ) AS testCase3;

存储的功能逻辑如下

CREATE DEFINER = `yourUserGoesHere`@`%` FUNCTION `countMatchingElements`(inFirstList VARCHAR(1000), inSecondList VARCHAR(1000))
 RETURNS tinyint(3) unsigned
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN
    DECLARE numReturn TINYINT UNSIGNED DEFAULT 0;
    DECLARE idsInFirstList TINYINT UNSIGNED;
    DECLARE currentListItem VARCHAR(255) DEFAULT '';
    DECLARE currentID TINYINT UNSIGNED;

    SET idsInFirstList = ( CHAR_LENGTH( inFirstList ) + 1 ) - CHAR_LENGTH( REPLACE( inFirstList , ',' , '' ) );
    SET currentID = 1;

    -- Loop over inFirstList, and for each element that is in inSecondList increment numReturn
    firstListLoop: REPEAT

        SET currentListItem = SUBSTRING_INDEX( SUBSTRING_INDEX( inFirstList , ',' , currentID ) , ',' , -1 );

        IF FIND_IN_SET( currentListItem , inSecondList ) THEN

            SET numReturn = numReturn + 1;

        END IF;

        SET currentID = currentID + 1;

    UNTIL currentID > idsInFirstList
    END REPEAT firstListLoop;

    RETURN numReturn;
END

这篇关于在mysql中比较两个逗号分隔的值并获取匹配的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆