0

I have a MySQL table with the following definition:

+--------+---------+------+-----+---------+-------+
| Field  | Type    | Null | Key | Default | Extra |
+--------+---------+------+-----+---------+-------+
| id     | int(11) | NO   | PRI | NULL    |       |
| numbers| json    | YES  |     | NULL    |       |
+--------+---------+------+-----+---------+-------+

The table has some sample data as follows:

+----+------+----------------------------------+
| id | numbers                                 |
+----+------+----------------------------------+
|  1 | [1,2,3,4,5]                             |
|  2 | [2,3,7,8,9]                             |
|  3 | [5,7,10,15]                             |
+----+------+----------------------------------+

How can I calculate the total number of matched numbers (2,3,7,10) for each card? For example:

+----+---------+
| ID | Matches |
+----+---------+
| 1  | 2       |
| 2  | 3       |
| 3  | 2       | 
+----+---------+
3
  • What is your MySQL version? Commented Oct 6, 2020 at 1:11
  • If numbers is equal [2,2] then you need the result of 1 or 2? Do not tell "the array cannot have duplicated values" - or prove this by table's CREATE TABLE with according CHECK constraint. Commented Oct 6, 2020 at 5:31
  • You can´t have duplicated numbers. Commented Oct 6, 2020 at 5:41

1 Answer 1

2

In MySQL 8+ you can cross join json_table() to get a row for each number ID combination (for the numbers in the JSON array of the ID). Then you can aggregate grouping by the ID and get the sum of instances where the number (from the JSON array) is in the list of numbers you search for.

SELECT t.id,
       sum(jt.number IN (2, 3, 7, 10)) matches
       FROM elbat t
            CROSS JOIN json_table(numbers, '$[*]' COLUMNS (number integer PATH '$')) jt
       GROUP BY t.id;

db<>fiddle

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

2 Comments

If need to check same logic in two other columns how to write that SQL? Lets say columns: line1, line2, line3.
@JúlioPontes: That's another, new question you might want to ask.

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.