1

I have a simple database table which has the following structure:

Teams       Id_1           Id_2            Id_3 

team_1       A              B                C

team_2       A              B                D

team_3       E              F                D

team_4       X              null            null

team_5       D              A                B

now i have a sample array of string IDs the value of which is: A B. I want to select the team/teams based on the maximum match of this data point with the database, for example, the result of the match should give me team_1, team_2 and team_5 as output. What is an efficient way to do this query on mysql? Thanks in Advance.

4
  • why is team 5 not returned? is the match position aware? Commented Oct 3, 2013 at 9:29
  • thnks..position does not matter. team_5 will be returned too..just need to match regardless of the position. Commented Oct 3, 2013 at 9:31
  • What about [B, A] array? What if it will be [A, B, D, F] array? I.e. what is your 'maximum match'? Commented Oct 3, 2013 at 9:33
  • [B A] array is same as [A B] array, i want to select the row/rows which have maximum number of matching values with the array, for example, [A B D F] will return team_2 and team_5 Commented Oct 3, 2013 at 9:39

2 Answers 2

1

Assuming you want those with the best match (so if searching for [D Z] it would find the 3 items with D but as nothing contains Z that would be ignored, then maybe something like this (untested):-

SELECT *
FROM SomeTable
CROSS JOIN
(
    SELECT MAX(IF(FIND_IN_SET(ID_1, REPLACE("A B", " ", ",")) > 0, 1, 0) + IF(FIND_IN_SET(ID_2, REPLACE("A B", " ", ",")) > 0, 1, 0) + IF(FIND_IN_SET(ID_3, REPLACE("A B", " ", ",")) > 0 > 0, 1, 0)) AS MaxCount
    FROM SomeTable
    WHERE FIND_IN_SET(ID_1, REPLACE("A B", " ", ",")) > 0
    OR FIND_IN_SET(ID_2, REPLACE("A B", " ", ",")) > 0
    OR FIND_IN_SET(ID_3, REPLACE("A B", " ", ",")) > 0
) Sub1
WHERE IF(FIND_IN_SET(SomeTable.ID_1, REPLACE("A B", " ", ",")) > 0, 1, 0) + IF(FIND_IN_SET(SomeTable.ID_2, REPLACE("A B", " ", ",")) > 0, 1, 0) + IF(FIND_IN_SET(SomeTable.ID_3, REPLACE("A B", " ", ",")) > 0 > 0, 1, 0) = Sub1.MaxCount

Note if the list passed was comma separated you could avoid using all the replace statements.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this. Take the ID field and pad with space (the separator). Pad search string also with space. Then check if you can find the padded ID in the padded search string.

Select *
From Tbl
Where ' ' + ID_1 + ' ' in ' ' + SearchStr + ' '
   Or ' ' + ID_2 + ' ' in ' ' + SearchStr + ' '
   Or ' ' + ID_3 + ' ' in ' ' + SearchStr + ' '

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.